/// <summary>
        ///     Generates the scriptSig.
        /// </summary>
        /// <param name="signature">
        ///     The transaction signature. For unsigned inputs this can be <c>null</c> in which case it is
        ///     encoded as an <c>OP_0</c>.
        /// </param>
        /// <param name="coldPubKey">A flag indicating whether the cold wallet versus the hot wallet is signing.</param>
        /// <param name="publicKey">The cold or hot wallet public key.</param>
        /// <returns>The scriptSig.</returns>
        public Script GenerateScriptSig(TransactionSignature signature, bool coldPubKey, PubKey publicKey)
        {
            Guard.NotNull(signature, nameof(signature));
            Guard.NotNull(publicKey, nameof(publicKey));

            return(new Script(
                       Op.GetPushOp(signature.ToBytes()),
                       coldPubKey ? OP_0 : OP_1,
                       Op.GetPushOp(publicKey.ToBytes())
                       ));
        }
 public WitScript GenerateWitScript(TransactionSignature signature, PubKey publicKey)
 {
     if (publicKey == null)
     {
         throw new ArgumentNullException("publicKey");
     }
     return(new WitScript(
                signature == null ? OpcodeType.OP_0 : Op.GetPushOp(signature.ToBytes()),
                Op.GetPushOp(publicKey.ToBytes())
                ));
 }
Пример #3
0
 public static void ReadWriteC(this BitcoinStream bs, ref PubKey pubKey)
 {
     if (bs.Serializing)
     {
         var bytes = pubKey.ToBytes();
         bs.Inner.Write(bytes, 0, 33);
     }
     else
     {
         pubKey = new PubKey(bs.Inner.ReadBytes(33));
     }
 }
Пример #4
0
 /// <summary>
 /// Generate atomic swap payment script to P2PK <paramref name="bobDestinationPubKey"/> with multisig refund
 /// </summary>
 /// <param name="aliceRefundPubKey">Alice public key for refund</param>
 /// <param name="bobRefundPubKey">Bob public key for refund</param>
 /// <param name="bobDestinationPubKey">Bob public key</param>
 /// <param name="secretHash">Secret hash</param>
 /// <returns>Atomic swap payment script</returns>
 public static Script GenerateP2PkSwapPayment(
     PubKey aliceRefundPubKey,
     PubKey bobRefundPubKey,
     PubKey bobDestinationPubKey,
     byte[] secretHash)
 {
     return(GenerateP2PkSwapPayment(
                aliceRefundPubKey: aliceRefundPubKey.ToBytes(),
                bobRefundPubKey: bobRefundPubKey.ToBytes(),
                bobDestinationPubKey: bobDestinationPubKey.ToBytes(),
                secretHash: secretHash));
 }
Пример #5
0
        public Wallet(string privateKey, Network env)
        {
            _env            = BinanceEnvironment.GetEnvironment(env);
            _privateKey     = new Key(Helpers.StringToByteArrayFastest(privateKey));
            _privateKeyStr  = privateKey;
            _publicKey      = _privateKey.PubKey.Compress();
            _publicKeyBytes = _publicKey.ToBytes();
            _AddressBytes   = _publicKey.Hash.ToBytes();
            _addressStr     = Bech32Engine.Encode(_env.Hrp, _AddressBytes);

            Init();
        }
        /// <summary>
        /// Returns `false` if the peer is already connected. otherwise return `true`.
        /// </summary>
        /// <param name="remoteEndPoint"></param>
        /// <param name="pubkey"></param>
        /// <param name="ct"></param>
        /// <returns>true if the peer is unknown</returns>
        public async ValueTask <bool> NewOutbound(EndPoint remoteEndPoint, PubKey pubkey, CancellationToken ct = default)
        {
            if (remoteEndPoint == null)
            {
                throw new ArgumentNullException(nameof(remoteEndPoint));
            }
            if (pubkey == null)
            {
                throw new ArgumentNullException(nameof(pubkey));
            }
            if (_connectionLoops.ContainsKey(remoteEndPoint))
            {
                _logger.LogError($"We have already connected to: {remoteEndPoint.ToEndpointString()}.");
                return(false);
            }

            try
            {
                var connectionContext = await _connectionFactory.ConnectAsync(remoteEndPoint, ct);

                var(descriptor, writeReceiver) = descriptorFactory.GetNewSocket(connectionContext.Transport.Output);
                var peerMan     = PeerManagerProvider.GetPeerManager("BTC");
                var initialSend = peerMan.NewOutboundConnection(descriptor, pubkey.ToBytes());
                await connectionContext.Transport.Output.WriteAsync(initialSend, ct);

                var flushResult = connectionContext.Transport.Output.FlushAsync(ct);
                if (!flushResult.IsCompleted)
                {
                    await flushResult.ConfigureAwait(false);
                }

                Func <Task> cleanup = async() =>
                {
                    _connectionLoops.TryRemove(connectionContext.RemoteEndPoint, out _);
                    await _repository.RemoveRemoteEndPoint(connectionContext.RemoteEndPoint, ct);
                };
                await _repository.SetRemoteEndPoint(remoteEndPoint, ct);

                var conn = new ConnectionLoop(connectionContext.Transport, descriptor, peerMan,
                                              writeReceiver, EventNotify.Writer, _loggerFactory.CreateLogger <ConnectionLoop>(), cleanup);
                _connectionLoops.TryAdd(remoteEndPoint, conn);
                Task.Run(() => conn.Start(ct));
            }

            catch (SocketException ex) when(ex.SocketErrorCode == SocketError.ConnectionRefused)
            {
                _logger.LogError($"{ex.Message}:{Environment.NewLine}{ex.StackTrace}");
                return(false);
            }

            return(true);
        }
Пример #7
0
 /// <summary>
 /// Generate atomic swap payment script to P2PKH <paramref name="bobAddress"/> with multisig refund
 /// </summary>
 /// <param name="aliceRefundPubKey">Alice public key for refund</param>
 /// <param name="bobRefundPubKey">Bob public key for refund</param>
 /// <param name="bobAddress">Bob target address</param>
 /// <param name="secretHash">Secret hash</param>
 /// <param name="expectedNetwork">Expected network necessary to get the correct hash address</param>
 /// <returns>Atomic swap payment script</returns>
 public static Script GenerateP2PkhSwapPayment(
     PubKey aliceRefundPubKey,
     PubKey bobRefundPubKey,
     string bobAddress,
     byte[] secretHash,
     Network expectedNetwork = null)
 {
     return(GenerateP2PkhSwapPayment(
                aliceRefundPubKey: aliceRefundPubKey.ToBytes(),
                bobRefundPubKey: bobRefundPubKey.ToBytes(),
                bobAddress: bobAddress,
                secretHash: secretHash,
                expectedNetwork: expectedNetwork));
 }
        private Key AssertKeys(string key, string pub)
        {
            if (key == null)
            {
                return(null);
            }
            Key k = new Key(TestUtils.ParseHex(key));

            if (pub != null)
            {
                PubKey p = new PubKey(TestUtils.ParseHex(pub));
                AssertEx.Equal(k.PubKey.ToBytes(), p.ToBytes());
            }
            return(k);
        }
Пример #9
0
        /*
         * https://github.com/lightningnetwork/lightning-rfc/blob/master/03-transactions.md#to_local-output
         *
         *   OP_IF
         *       # Penalty transaction
         *       <revocationpubkey>
         *   OP_ELSE
         *       `to_self_delay`
         *       OP_CSV
         *       OP_DROP
         *       <local_delayedpubkey>
         *   OP_ENDIF
         *   OP_CHECKSIG
         *
         */
        public static Script ToLocal(PubKey localRevocationPubkey, PubKey localDelayedPaymentPubkey, ushort toSelfDelay)
        {
            List <Op> opList = new List <Op>();

            opList.Add(OpcodeType.OP_IF);
            opList.Add(Op.GetPushOp(localRevocationPubkey.ToBytes()));
            opList.Add(OpcodeType.OP_ELSE);
            opList.Add(Op.GetPushOp(toSelfDelay));
            opList.Add(OpcodeType.OP_CHECKSEQUENCEVERIFY);
            opList.Add(OpcodeType.OP_DROP);
            opList.Add(Op.GetPushOp(localDelayedPaymentPubkey.ToBytes()));
            opList.Add(OpcodeType.OP_ENDIF);
            opList.Add(OpcodeType.OP_CHECKSIG);

            return(new Script(opList));
        }
Пример #10
0
        private static void GeneratePublicPrivateKeys(string passphrase, string keyPath, bool isMultiSigOutput = true)
        {
            // Generate keys for signing.
            var    mnemonicForSigningKey = new Mnemonic(Wordlist.English, WordCount.Twelve);
            PubKey signingPubKey         = mnemonicForSigningKey.DeriveExtKey(passphrase).PrivateKey.PubKey;

            // Generate keys for migning.
            var tool = new KeyTool(keyPath);

            Key key = tool.GeneratePrivateKey();

            string savePath = tool.GetPrivateKeySavePath();

            tool.SavePrivateKey(key);
            PubKey miningPubKey = key.PubKey;

            Console.WriteLine($"Your Masternode Public Key: {Encoders.Hex.EncodeData(miningPubKey.ToBytes(false))}");
            Console.WriteLine($"-----------------------------------------------------------------------------");

            if (isMultiSigOutput)
            {
                Console.WriteLine(
                    $"Your Masternode Signing Key: {Encoders.Hex.EncodeData(signingPubKey.ToBytes(false))}");
                Console.WriteLine(Environment.NewLine);
                Console.WriteLine(
                    $"------------------------------------------------------------------------------------------");
                Console.WriteLine(
                    $"-- Please keep the following 12 words for yourself and note them down in a secure place --");
                Console.WriteLine(
                    $"------------------------------------------------------------------------------------------");
                Console.WriteLine($"Your signing mnemonic: {string.Join(" ", mnemonicForSigningKey.Words)}");
            }

            if (passphrase != null)
            {
                Console.WriteLine(Environment.NewLine);
                Console.WriteLine($"Your passphrase: {passphrase}");
            }

            Console.WriteLine(Environment.NewLine);
            Console.WriteLine($"------------------------------------------------------------------------------------------------------------");
            Console.WriteLine($"-- Please save the following file in a secure place, you'll need it when the federation has been created. --");
            Console.WriteLine($"------------------------------------------------------------------------------------------------------------");
            Console.WriteLine($"File path: {savePath}");
            Console.WriteLine(Environment.NewLine);
        }
Пример #11
0
        public static Script CreateOffchainScript(PubKey pubKey1, PubKey revokePubKey, PubKey lockedPubKey, int delay)
        {
            var multisigScriptOps = PayToMultiSigTemplate.Instance.GenerateScriptPubKey
                                        (2, pubKey1, revokePubKey).ToOps();
            var ops = new List <Op>();

            ops.Add(OpcodeType.OP_IF);
            ops.AddRange(multisigScriptOps);
            ops.Add(OpcodeType.OP_ELSE);
            ops.Add(Op.GetPushOp(delay));
            ops.Add(OpcodeType.OP_CHECKSEQUENCEVERIFY);
            ops.Add(OpcodeType.OP_DROP);
            ops.Add(Op.GetPushOp(lockedPubKey.ToBytes()));
            ops.Add(OpcodeType.OP_CHECKSIG);
            ops.Add(OpcodeType.OP_ENDIF);
            return(new Script(ops.ToArray()));
        }
Пример #12
0
        private Script CreateScript(PubKey pbk1, PubKey pbk2, PubKey singlePk)
        {
            var multisigScriptOps = PayToMultiSigTemplate.Instance.GenerateScriptPubKey
                                        (2, pbk1, pbk2).ToOps();
            List <Op> ops = new List <Op>();

            ops.Add(OpcodeType.OP_IF);
            ops.AddRange(multisigScriptOps);
            ops.Add(OpcodeType.OP_ELSE);
            ops.Add(Op.GetPushOp(144));
            ops.Add(OpcodeType.OP_CHECKSEQUENCEVERIFY);
            ops.Add(OpcodeType.OP_DROP);
            ops.Add(Op.GetPushOp(singlePk.ToBytes()));
            ops.Add(OpcodeType.OP_CHECKSIG);
            ops.Add(OpcodeType.OP_ENDIF);
            return(new Script(ops.ToArray()));
        }
Пример #13
0
        string GenerateAddress(PubKey pubKey)
        {
            var         pk      = pubKey.ToBytes();
            HMACBlake2B blake2b = new HMACBlake2B(PKHASH_BIT_SIZE);

            blake2b.Initialize();

            var pkNew = blake2b.ComputeHash(pk);

            int prefixLen = tz2.Length;

            byte[] msg = new byte[prefixLen + pkNew.Length];

            Array.Copy(tz2, 0, msg, 0, tz2.Length);
            Array.Copy(pkNew, 0, msg, prefixLen, pkNew.Length);

            return(Base58CheckEncoding.Encode(msg));
        }
Пример #14
0
        public void testSameSINisDerived_NB()
        {
            //pubkey check
            PubKey nbPub = _nbKey.PubKey.Decompress();

            Assert.AreEqual(
                "04134f2e64c201d3fefae9f2fd5041a302130193dfec53de276e04cdc343a5ee8192a72a9e06ab057287442860aad70e7238201c7da0ada05b84eae18de530b1bf",
                BitConverter.ToString(nbPub.ToBytes()).Replace("-", String.Empty).ToLower());

            string sin = KeyUtils.deriveSIN(_nbKey);

            //pubkey check
            Assert.AreEqual(
                "04134f2e64c201d3fefae9f2fd5041a302130193dfec53de276e04cdc343a5ee8192a72a9e06ab057287442860aad70e7238201c7da0ada05b84eae18de530b1bf",
                BitConverter.ToString(_ecKey.PubKey).Replace("-", String.Empty).ToLower());
            //SIN code generated check
            Assert.AreEqual("TfJBAqpGcvhCEVhnZYacwo21d9BMkfAWpLV", sin);
        }
Пример #15
0
        public void bloom_create_insert_key()
        {
            string        strSecret = "5Kg1gnAjaLfKiwhhPpGS3QfRg2m6awQvaj98JCZBZQ5SuS2F15C";
            BitcoinSecret vchSecret = Network.Main.CreateBitcoinSecret(strSecret);
            PubKey        pubkey    = vchSecret.PrivateKey.PubKey;

            var filter = new BloomFilter(2, 0.001, 0, BloomFlags.UPDATE_ALL);

            filter.Insert(pubkey.ToBytes());
            filter.Insert(pubkey.Hash.ToBytes());

            var ms            = new MemoryStream();
            var bitcoinStream = new BitcoinStream(ms, true);

            bitcoinStream.ReadWrite(filter);

            byte[] expected = ParseHex("038fc16b080000000000000001");

            AssertEx.CollectionEquals(expected, ms.ToArray());
        }
Пример #16
0
        public static Script GetRedeemScript(BtcAddress address)
        {
            var ownerPublicKey      = new PubKey(address.Teammate.PublicKey);
            var cosignersPublicKeys = address.Cosigners.OrderBy(x => x.KeyOrder).Select(x => new PubKey(x.Teammate.PublicKey)).ToList();
            var n = cosignersPublicKeys.Count;

            Op[] ops = new Op[7 + n];

            ops[0] = Op.GetPushOp(ownerPublicKey.ToBytes());
            ops[1] = OpcodeType.OP_CHECKSIGVERIFY;
            if (n > 6)
            {
                ops[2] = OpcodeType.OP_3;
            }
            else if (n > 3)
            {
                ops[2] = OpcodeType.OP_2;
            }
            else if (n > 0)
            {
                ops[2] = OpcodeType.OP_1;
            }
            else
            {
                ops[2] = OpcodeType.OP_0;
            }

            for (int i = 0; i < n; i++)
            {
                var pubKey = cosignersPublicKeys[i];
                ops[3 + i] = Op.GetPushOp(pubKey.ToBytes());
            }
            ops[3 + n] = (OpcodeType)(80 + n);
            ops[4 + n] = OpcodeType.OP_CHECKMULTISIG;
            ops[5 + n] = Op.GetPushOp(new BigInteger(address.Teammate.Team.Id));
            ops[6 + n] = OpcodeType.OP_DROP;

            Script redeemScript = new Script(ops);

            return(redeemScript);
        }
Пример #17
0
        private bool TryMirrorPubKey(PubKey pubKey, out PubKey mirrorPubKey)
        {
            var pubKeyStr       = Helpers.ByteArrayToString(pubKey.ToBytes());
            var mirrorPubKeyStr =
                pubKeyStr.Substring(0, 8)
                + pubKeyStr.Substring(8, 2)
                + Helpers.ReverseString(pubKeyStr.Substring(10, 54))
                + pubKeyStr.Substring(64, 2);
            var mirrorPubKeyBytes = Helpers.StringToByteArray(mirrorPubKeyStr);

            try
            {
                mirrorPubKey = new PubKey(mirrorPubKeyBytes, false);
                return(false);
            }
            catch (Exception)
            {
                //Console.WriteLine(ex.InnerException);
                mirrorPubKey = new PubKey(mirrorPubKeyBytes, true);
                return(true);
            }
        }
Пример #18
0
        public static string FromPublicKey(PubKey publicKey, byte publicKeyHash = 0)
        {
            MemoryStream stream = new MemoryStream();

            using (BinaryWriter writer = new BinaryWriter(stream))
            {
                var bytes = publicKey.ToBytes();

                if (publicKeyHash != 0)
                {
                    writer.Write(publicKeyHash);
                }
                else
                {
                    writer.Write(Configuration.Network.Get().GetPublicKeyHash());
                }

                writer.Write(Ripemd160.ComputeHash(bytes, 0, bytes.Length));

                return(Encoders.Base58Check.EncodeData(stream.ToArray()));
            }
        }
        private Script CreateOffchainScript(PubKey pubKey1, PubKey pubKey2, PubKey lockedPubKey)
        {
            var multisigScriptOps = PayToMultiSigTemplate.Instance.GenerateScriptPubKey
                                        (2, pubKey1, pubKey2).ToOps();
            var ops = new List <Op>();

            ops.Add(OpcodeType.OP_IF);
            ops.AddRange(multisigScriptOps);
            ops.Add(OpcodeType.OP_ELSE);
            ops.Add(Op.GetPushOp(OneDayDelay));
            ops.Add(OpcodeType.OP_CHECKSEQUENCEVERIFY);
            ops.Add(OpcodeType.OP_DROP);
            ops.Add(Op.GetPushOp(lockedPubKey.ToBytes()));
            ops.Add(OpcodeType.OP_CHECKSIG);
            ops.Add(OpcodeType.OP_ENDIF);

            //for unique script address per commitment
            ops.Add(Op.GetPushOp(Guid.NewGuid().ToByteArray()));
            ops.Add(OpcodeType.OP_DROP);

            return(new Script(ops.ToArray()));
        }
Пример #20
0
        public static byte[] PubKeyToBytes(PubKey pubkey)
        {
            /* Convert a PubKey back into a byte array. Note
             * that no assumptions are made about padding schemes, and
             * the data storage protocol therefore needs to be robust
             * enough to handle trailing empty or garbage bytes.
             */

            var decoded = new MemoryStream();

            byte[] temp;

            temp = pubkey.ToBytes();

            // Use an offset to trim off the 1 prefix byte
            if (temp.Length < 65)
            {
                throw new Exception("Decoded public key too short, data corrupted?");
            }
            decoded.Write(temp, 1, 64);

            return(decoded.ToArray());
        }
Пример #21
0
        public static Script CreateEscrow(PubKey[] keys, PubKey redeem, LockTime timeout)
        {
            keys = keys.OrderBy(o => o.ToHex()).ToArray();
            List <Op> ops = new List <Op>();

            ops.Add(OpcodeType.OP_DEPTH);
            ops.Add(OpcodeType.OP_3);
            ops.Add(OpcodeType.OP_EQUAL);
            ops.Add(OpcodeType.OP_IF);
            ops.Add(OpcodeType.OP_2);
            ops.Add(Op.GetPushOp(keys[0].ToBytes()));
            ops.Add(Op.GetPushOp(keys[1].ToBytes()));
            ops.Add(OpcodeType.OP_2);
            ops.Add(OpcodeType.OP_CHECKMULTISIG);
            ops.Add(OpcodeType.OP_ELSE);
            ops.Add(Op.GetPushOp(timeout));
            ops.Add(OpcodeType.OP_CHECKLOCKTIMEVERIFY);
            ops.Add(OpcodeType.OP_DROP);
            ops.Add(Op.GetPushOp(redeem.ToBytes()));
            ops.Add(OpcodeType.OP_CHECKSIG);
            ops.Add(OpcodeType.OP_ENDIF);
            return(new Script(ops.ToArray()));
        }
        public static bool VerifySignature(uint256 message, UnblindedSignature signature, PubKey signerPubKey)
        {
            if (!Context.Instance.TryCreatePubKey(signerPubKey.ToBytes(), out var signerECPubkey))
            {
                throw new FormatException("Invalid signer pubkey.");
            }

            var P = signerECPubkey.Q;

            var sG = (signature.S * EC.G).ToGroupElement();
            var cP = P * signature.C;
            var R  = cP + sG;
            var t  = R.ToGroupElement().x.Normalize();

            using var sha = new SHA256();
            Span <byte> tmp = stackalloc byte[32];

            message.ToBytes(tmp, false);
            sha.Write(tmp);
            t.WriteToSpan(tmp);
            sha.Write(tmp);
            sha.GetHash(tmp);
            return(new Scalar(tmp) == signature.C);
        }
Пример #23
0
        public async Task <bool> CompleteCreation(string name, string userId, ECDSASignature sig, PubKey pubKey)
        {
            try
            {
                await using var dbContext = _contextFactory.CreateContext();
                var user = await dbContext.Users.Include(applicationUser => applicationUser.Fido2Credentials)
                           .FirstOrDefaultAsync(applicationUser => applicationUser.Id == userId);

                var pubkeyBytes = pubKey.ToBytes();
                if (!CreationStore.TryGetValue(userId.ToLowerInvariant(), out var k1) || user == null || await dbContext.Fido2Credentials.AnyAsync(credential => credential.Type == Fido2Credential.CredentialType.LNURLAuth && credential.Blob == pubkeyBytes))
                {
                    return(false);
                }

                if (!global::LNURL.LNAuthRequest.VerifyChallenge(sig, pubKey, k1))
                {
                    return(false);
                }

                var newCredential = new Fido2Credential()
                {
                    Name = name, ApplicationUserId = userId, Type = Fido2Credential.CredentialType.LNURLAuth, Blob = pubkeyBytes
                };

                await dbContext.Fido2Credentials.AddAsync(newCredential);

                await dbContext.SaveChangesAsync();

                CreationStore.Remove(userId, out _);
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Пример #24
0
        /*
         * https://github.com/lightningnetwork/lightning-rfc/blob/master/03-transactions.md#received-htlc-outputs
         *
         # To remote node with revocation key
         #  OP_DUP OP_HASH160 <RIPEMD160(SHA256(revocationpubkey))> OP_EQUAL
         #  OP_IF
         #      OP_CHECKSIG
         #  OP_ELSE
         #      <remote_htlcpubkey> OP_SWAP
         #          OP_SIZE 32 OP_EQUAL
         #      OP_IF
         # To local node via HTLC-success transaction.
         #          OP_HASH160 <RIPEMD160(payment_hash)> OP_EQUALVERIFY
         #          2 OP_SWAP <local_htlcpubkey> 2 OP_CHECKMULTISIG
         #      OP_ELSE
         # To remote node after timeout.
         #          OP_DROP <cltv_expiry> OP_CHECKLOCKTIMEVERIFY OP_DROP
         #          OP_CHECKSIG
         #      OP_ENDIF
         #  OP_ENDIF
         #
         */
        public static Script ReceivedHtlc(PubKey localHtlcPubkey, PubKey remoteHtlcPubkey, PubKey localRevocationPubkey,
                                          byte[] paymentHash, uint expiry)
        {
            List <Op> opList = new List <Op>();

            opList.Add(OpcodeType.OP_DUP);
            opList.Add(OpcodeType.OP_HASH160);
            opList.Add(Op.GetPushOp(Hashes.Hash160(localRevocationPubkey.ToBytes()).ToBytes()));
            opList.Add(OpcodeType.OP_EQUAL);
            opList.Add(OpcodeType.OP_IF);
            opList.Add(OpcodeType.OP_CHECKSIG);
            opList.Add(OpcodeType.OP_ELSE);
            opList.Add(Op.GetPushOp(remoteHtlcPubkey.ToBytes()));
            opList.Add(OpcodeType.OP_SWAP);
            opList.Add(OpcodeType.OP_SIZE);
            opList.Add(Op.GetPushOp(32));
            opList.Add(OpcodeType.OP_EQUAL);
            opList.Add(OpcodeType.OP_IF);
            opList.Add(OpcodeType.OP_HASH160);
            opList.Add(Op.GetPushOp(Hashes.RIPEMD160(paymentHash, paymentHash.Length)));
            opList.Add(OpcodeType.OP_EQUALVERIFY);
            opList.Add(OpcodeType.OP_2);
            opList.Add(OpcodeType.OP_SWAP);
            opList.Add(Op.GetPushOp(localHtlcPubkey.ToBytes()));
            opList.Add(OpcodeType.OP_2);
            opList.Add(OpcodeType.OP_CHECKMULTISIG);
            opList.Add(OpcodeType.OP_ELSE);
            opList.Add(OpcodeType.OP_DROP);
            opList.Add(Op.GetPushOp(expiry));
            opList.Add(OpcodeType.OP_CHECKLOCKTIMEVERIFY);
            opList.Add(OpcodeType.OP_DROP);
            opList.Add(OpcodeType.OP_CHECKSIG);
            opList.Add(OpcodeType.OP_ENDIF);
            opList.Add(OpcodeType.OP_ENDIF);
            return(new Script(opList));
        }
Пример #25
0
        private static void GeneratePublicPrivateKeys(string passphrase)
        {
            // Generate keys for signing.
            var    mnemonicForSigningKey = new Mnemonic(Wordlist.English, WordCount.Twelve);
            PubKey signingPubKey         = mnemonicForSigningKey.DeriveExtKey(passphrase).PrivateKey.PubKey;

            // Generate keys for migning.
            var tool = new KeyTool(new DataFolder(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)));
            Key key  = tool.GeneratePrivateKey();

            string savePath = tool.GetPrivateKeySavePath();

            tool.SavePrivateKey(key);
            PubKey miningPubKey = key.PubKey;

            Console.WriteLine($"-----------------------------------------------------------------------------");
            Console.WriteLine($"-- Please give the following 2 public keys to the federation administrator --");
            Console.WriteLine($"-----------------------------------------------------------------------------");
            Console.WriteLine($"1. Your signing pubkey: {Encoders.Hex.EncodeData(signingPubKey.ToBytes(false))}");
            Console.WriteLine($"2. Your mining pubkey: {Encoders.Hex.EncodeData(miningPubKey.ToBytes(false))}");
            Console.WriteLine(Environment.NewLine);
            Console.WriteLine($"------------------------------------------------------------------------------------------");
            Console.WriteLine($"-- Please keep the following 12 words for yourself and note them down in a secure place --");
            Console.WriteLine($"------------------------------------------------------------------------------------------");
            Console.WriteLine($"Your signing mnemonic: {string.Join(" ", mnemonicForSigningKey.Words)}");
            if (passphrase != null)
            {
                Console.WriteLine($"Your passphrase: {passphrase}");
            }
            Console.WriteLine(Environment.NewLine);
            Console.WriteLine($"------------------------------------------------------------------------------------------------------------");
            Console.WriteLine($"-- Please save the following file in a secure place, you'll need it when the federation has been created. --");
            Console.WriteLine($"------------------------------------------------------------------------------------------------------------");
            Console.WriteLine($"File path: {savePath}");
            Console.WriteLine(Environment.NewLine);
        }
            public uint256 BlindMessage(uint256 message, PubKey rpubkey, PubKey signerPubKey)
            {
                var         ctx = new ECMultGenContext();
                int         overflow;
                Span <byte> tmp = stackalloc byte[32];

                if (!Context.Instance.TryCreatePubKey(signerPubKey.ToBytes(), out var signerECPubkey))
                {
                    throw new FormatException("Invalid signer pubkey.");
                }
                if (!Context.Instance.TryCreatePubKey(rpubkey.ToBytes(), out var rECPubKey))
                {
                    throw new FormatException("Invalid r pubkey.");
                }
                var P = signerECPubkey.Q;
                var R = rECPubKey.Q.ToGroupElementJacobian();
                var t = FE.Zero;

retry:

                RandomUtils.GetBytes(tmp);
                _v = new Scalar(tmp, out overflow);
                if (overflow != 0 || _v.IsZero)
                {
                    goto retry;
                }
                RandomUtils.GetBytes(tmp);
                _w = new Scalar(tmp, out overflow);
                if (overflow != 0 || _v.IsZero)
                {
                    goto retry;
                }
                var A1 = ctx.MultGen(_v);
                var A2 = _w * P;
                var A  = R.AddVariable(A1, out _).AddVariable(A2, out _).ToGroupElement();

                t = A.x.Normalize();
                if (t.IsZero)
                {
                    goto retry;
                }
                using (var sha = new SHA256())
                {
                    message.ToBytes(tmp, false);
                    sha.Write(tmp);
                    t.WriteToSpan(tmp);
                    sha.Write(tmp);
                    sha.GetHash(tmp);
                }
                _c = new Scalar(tmp, out overflow);
                if (overflow != 0 || _c.IsZero)
                {
                    goto retry;
                }
                var cp = _c.Add(_w.Negate(), out overflow);                 // this is sent to the signer (blinded message)

                if (cp.IsZero || overflow != 0)
                {
                    goto retry;
                }
                cp.WriteToSpan(tmp);
                return(new uint256(tmp));
            }
Пример #27
0
		private Key AssertKeys(string key, string pub)
		{
			if(key == null)
				return null;
			Key k = new Key(TestUtils.ParseHex(key));
			if(pub != null)
			{
				PubKey p = new PubKey(TestUtils.ParseHex(pub));
				AssertEx.Equal(k.PubKey.ToBytes(), p.ToBytes());
			}
			return k;
		}
        public bool Verify(uint256 m, PubKey pubkey, SchnorrSignature sig)
        {
            if (sig.R.CompareTo(PP) >= 0 || sig.S.CompareTo(Secp256k1.N) >= 0)
            {
                return(false);
            }
            var e = new BigInteger(1, Hashes.SHA256(Utils.BigIntegerToBytes(sig.R, 32).Concat(pubkey.ToBytes(), m.ToBytes()))).Mod(Secp256k1.N);
            var q = pubkey.ECKey.GetPublicKeyParameters().Q.Normalize();
            var P = Secp256k1.Curve.CreatePoint(q.XCoord.ToBigInteger(), q.YCoord.ToBigInteger());

            var R = Secp256k1.G.Multiply(sig.S).Add(P.Multiply(Secp256k1.N.Subtract(e))).Normalize();

            if (R.IsInfinity ||
                R.XCoord.ToBigInteger().CompareTo(sig.R) != 0 ||
                BigInteger.Jacobi(R.YCoord.ToBigInteger(), PP) != 1)
            {
                return(false);
            }

            return(true);
        }
Пример #29
0
 public PubKeyId(PubKey pubKey)
 {
     _DestBytes = pubKey.ToBytes();
 }
        private static string GetBase58(PubKey blindingKey, BitcoinAddress address)
        {
            if (address == null)
            {
                throw new ArgumentNullException(nameof(address));
            }
            if (blindingKey == null)
            {
                throw new ArgumentNullException(nameof(blindingKey));
            }

            if (address is BitcoinBlindedAddress ba)
            {
                address = ba.UnblindedAddress;
            }
            if (!(address is IBase58Data))
            {
                throw new ArgumentException("Unsupported address");
            }

            var network = address.Network;
            var keyId   = address.ScriptPubKey.GetDestination();

            if (keyId == null)
            {
                throw new ArgumentException("The passed address can't be reduced to a hash");
            }
            var bytes = address.Network.GetVersionBytes(Base58Type.BLINDED_ADDRESS, true).Concat(network.GetVersionBytes(((IBase58Data)address).Type, true), blindingKey.ToBytes(), keyId.ToBytes());

            return(Encoders.Base58Check.EncodeData(bytes));
        }
Пример #31
0
        public void CanCreatePayment()
        {
            var tests = new[]
            {
                new CanCreatePaymentData
                {
                    //sx stealth-newkey
                    StealthAddress = "vJmtjxSDxNPXL4RNapp9ARdqKz3uJyf1EDGjr1Fgqs9c8mYsVH82h8wvnA4i5rtJ57mr3kor1EVJrd4e5upACJd588xe52yXtzumxj",

                    ScanSecret = "3e49e7257cb31db997edb1cf8299af0f37e2663e2260e4b8033e49d39a6d02f2",
                    ScanPubKey = "025e58a31122b38c86abc119b9379fe247410aee87a533f9c07b189aef6c3c1f52",

                    SpendSecret = "aa3db0cfb3edc94de4d10f873f8190843f2a17484f6021a95a7742302c744748",
                    SpendPubKey = "03616562c98e7d7b74be409a787cec3a912122f3fb331a9bee9b0b73ce7b9f50af",

                    //sx newkey | sx wif-to-secret
                    EphemSecret = "9e63abaf8dcd5ea3919e6de0b6c544e00bf51bf92496113a01d6e369944dc091",
                    EphemPubKey = "03403d306ec35238384c7e340393335f9bc9bb4a2e574eb4e419452c4ea19f14b0",

                    //sx steatlh-uncover-secret [EphemPubKey] [ScanSecret] [SpendSecret]
                    StealthSecret = "4e422fb1e5e1db6c1f6ab32a7706d368ceb385e7fab098e633c5c5949c3b97cd",
                    //sx stealth-initiate [EphemSecret] [ScanPubKey] [SpendPubKey] (for sender)
                    //or
                    //sx stealth-uncover [EphemPubKey] [ScanSecret] [SpendPubKey]  (for receiver)
                    StealthPubKey = "02726112ad39cb6bf848b1b1ef30b88e35286bf99f746c2be575f96c0e02a9357c",
                },

                //Need padding for to find the stealth secret
                new CanCreatePaymentData {
                    StealthAddress = "vJmyTEybwCKz7W8y6vP62jo7RoyfLneiANcPLBBNYwn98EXzQRStMKqKGRiZhqscuQ6WKy2J3U3zfx72V3b2J6YvxxBcxUj4XMDsw7",
                    ScanSecret     = "2f517d81cf30e47dbf4809321275bbfd92192af81a6141a17aa53e40bd28fe36",
                    ScanPubKey     = "039d91ae0eebea6dc500fb57b704abce3d3fa700cc762a52bc5dcaee27770a8402",
                    SpendSecret    = "71e33219884fc27011f8da9adcc730f0c2e940759bdb1b615764492bce04fcea",
                    SpendPubKey    = "021a3d5b40ec83fc58b5a23207eb9c99b741d8f0e9f8b80f04f49cec915b540c40",
                    EphemSecret    = "578ffe42c0fbfb324a31f41dbbcd8b1f910ce2f4d803444a83b18ae9f8ccd97e",
                    EphemPubKey    = "03c190be0a1c6e50577b3dd637b1fff9344de31c2544ff3d815535c0515711150f",
                    StealthSecret  = "006d138b4bcef0f09c8784c0cc68f2be4497a1a822d8d7b0519c5c0378b5cb45",
                    StealthPubKey  = "0223a99278a5279ea93718503a42377067e72960eb808d8bff6defdd95d4feff76"
                }
            };

            foreach (CanCreatePaymentData test in tests)
            {
                Key scan    = AssertKeys(test.ScanSecret, test.ScanPubKey);
                Key spend   = AssertKeys(test.SpendSecret, test.SpendPubKey);
                Key ephem   = AssertKeys(test.EphemSecret, test.EphemPubKey);
                Key stealth = AssertKeys(test.StealthSecret, test.StealthPubKey);

                BitcoinStealthAddress address = spend.PubKey.CreateStealthAddress(scan.PubKey, KnownNetworks.Main);
                Assert.Equal(test.StealthAddress, address.ToString());
                //Try roundtrip
                address = new BitcoinStealthAddress(address.ToBytes(), KnownNetworks.Main);
                Assert.Equal(test.StealthAddress, address.ToString());

                StealthPayment payment      = address.CreatePayment(ephem);
                Key            generatedKey = spend.Uncover(scan, payment.Metadata.EphemKey);
                if (stealth != null)
                {
                    Assert.Equal(stealth.PubKey.Hash, payment.StealthKeys[0].ID);
                    Assert.Equal(stealth.ToBytes(), generatedKey.ToBytes());
                }
                PubKey uncoveredSender    = spend.PubKey.UncoverSender(ephem, scan.PubKey);
                PubKey uncovertedReceiver = spend.PubKey.UncoverReceiver(scan, ephem.PubKey);

                AssertEx.CollectionEquals(uncoveredSender.ToBytes(), uncovertedReceiver.ToBytes());
                AssertEx.CollectionEquals(generatedKey.PubKey.ToBytes(), uncovertedReceiver.ToBytes());

                var transaction = new Transaction();
                payment.AddToTransaction(transaction, 100);
            }
        }