Beispiel #1
0
 public static bool TryParse(string str, out PartialSignature?sig)
 {
     if (str == null)
     {
         throw new ArgumentNullException(nameof(str));
     }
     sig = null;
     try
     {
         var bytes = Encoders.Hex.DecodeData(str);
         if (bytes.Length < 2 + 33 + 1 || bytes[0] != 0x22 || bytes[1] != 0x02)
         {
             return(false);
         }
         var pk     = new NBitcoin.PubKey(bytes.AsSpan().Slice(2, 33).ToArray());
         var siglen = bytes[2 + 33];
         if (siglen < 75 && bytes.Length != 2 + 33 + 1 + siglen)
         {
             return(false);
         }
         var sigBytes = bytes.AsSpan().Slice(2 + 33 + 1).ToArray();
         if (!TransactionSignature.IsValid(sigBytes))
         {
             return(false);
         }
         var s = new TransactionSignature(sigBytes);
         sig = new PartialSignature(pk, s);
         return(true);
     }
     catch
     {
         return(false);
     }
 }
Beispiel #2
0
        public static StealthPayment[] GetPayments(Transaction transaction, PubKey[] spendKeys, BitField bitField, Key scan)
        {
            List<StealthPayment> result = new List<StealthPayment>();
            for(int i = 0 ; i < transaction.Outputs.Count ; i++)
            {
                var metadata = StealthMetadata.TryParse(transaction.Outputs[i].ScriptPubKey);
                if(metadata != null && bitField.Match(metadata.BitField))
                {
                    var payment = new StealthPayment(transaction.Outputs[i + 1].ScriptPubKey, metadata);
                    if(scan != null && spendKeys != null)
                    {
                        if(payment.StealthKeys.Length != spendKeys.Length)
                            continue;

                        var expectedStealth = spendKeys.Select(s => s.UncoverReceiver(scan, metadata.EphemKey)).ToList();
                        foreach(var stealth in payment.StealthKeys)
                        {
                            var match = expectedStealth.FirstOrDefault(expected => expected.ID == stealth.ID);
                            if(match != null)
                                expectedStealth.Remove(match);
                        }
                        if(expectedStealth.Count != 0)
                            continue;
                    }
                    result.Add(payment);
                }
            }
            return result.ToArray();
        }
		public bool Check(PubKey pubKey, Script scriptPubKey, Transaction tx, uint nIndex, ScriptVerify verify = ScriptVerify.Standard)
		{
			return new ScriptEvaluationContext()
			{
				ScriptVerify = verify,
				SigHash = SigHash
			}.CheckSig(this, pubKey, scriptPubKey, tx, nIndex);
		}
 public BitcoinOracleConnector(string network, string endpoint, string pkcsUser, string hsmKey)
 {
     this.pkcsUser = pkcsUser;
     this.hsmKey   = hsmKey;
     this.network  = network == "testnet" ? NetworkType.Testnet : NetworkType.Mainnet;
     client        = new ExplorerClient(new NBXplorerNetworkProvider(this.network).GetBTC(), new Uri(endpoint));
     pubKey        = new NBitcoin.PubKey("045138d46c0e99a3b94a49551581097bae7162bdbd70dbddc580963f98b2771bbee5ecf367dfa34b2c9952269691f87153cbf2a1589c177dfd66ac6735b92f6cf7");
 }
 public GetWalletPubKeyResponse(byte[] bytes)
 {
     MemoryStream ms = new MemoryStream(bytes);
     var len = ms.ReadByte();
     UncompressedPublicKey = new PubKey(ms.ReadBytes(len));
     len = ms.ReadByte();
     var addr = Encoding.ASCII.GetString(ms.ReadBytes(len));
     Address = BitcoinAddress.GetFromBase58Data(addr);
     ChainCode = ms.ReadBytes(32);
 }
Beispiel #6
0
 static Coin CreateTransactionFeeCoin(PubKey destination, NoSqlTransactionRepository txRepo)
 {
     var bitcoinProviderTransaction = new Transaction()
     {
         Outputs =
         {
             new TxOut("0.0001" , destination)
         }
     };
     txRepo.Put(bitcoinProviderTransaction.GetHash(), bitcoinProviderTransaction);
     return new Coin(new OutPoint(bitcoinProviderTransaction, 0),
         bitcoinProviderTransaction.Outputs[0]);
 }
Beispiel #7
0
 public StealthPayment(int sigCount, PubKey[] spendPubKeys, Key privateKey, PubKey publicKey, StealthMetadata metadata)
 {
     Metadata = metadata;
     if(sigCount == 1 && spendPubKeys.Length == 1)
     {
         var template = new PayToPubkeyHashTemplate();
         SpendableScript = template.GenerateScriptPubKey(spendPubKeys[0].Uncover(privateKey, publicKey).ID);
     }
     else
     {
         var template = new PayToMultiSigTemplate();
         SpendableScript = template.GenerateScriptPubKey(sigCount, spendPubKeys.Select(p => p.Uncover(privateKey, publicKey)).ToArray());
     }
     ParseSpendable();
 }
		public bool Check(PubKey pubKey, Script scriptPubKey, IndexedTxIn txIn, ScriptVerify verify = ScriptVerify.Standard)
		{
			return Check(pubKey, scriptPubKey, txIn.Transaction, txIn.Index, verify);
		}
Beispiel #9
0
 public PubKey Uncover(Key priv, PubKey pub)
 {
     var curve = ECKey.CreateCurve();
     var hash = GetStealthSharedSecret(priv,pub);
     //Q' = Q + cG
     var qprim = curve.G.Multiply(new BigInteger(1, hash)).Add(curve.Curve.DecodePoint(this.ToBytes()));
     return new PubKey(qprim.GetEncoded()).Compress(this.IsCompressed);
 }
Beispiel #10
0
 public PubKey UncoverSender(Key ephem, PubKey scan)
 {
     return Uncover(ephem, scan);
 }
 public bool Check(Network network, PubKey pubKey, Script scriptPubKey, IndexedTxIn txIn, ScriptVerify verify = ScriptVerify.Standard)
 {
     return(this.Check(network, pubKey, scriptPubKey, txIn.Transaction, txIn.Index, verify));
 }
        public bool Check(string passphrase, BitcoinAddress expectedAddress)
        {
            //Derive passfactor using scrypt with ownerentropy and the user's passphrase and use it to recompute passpoint
            byte[] passfactor = BitcoinEncryptedSecretEC.CalculatePassFactor(passphrase, LotSequence, OwnerEntropy);
            //Derive decryption key for pointb using scrypt with passpoint, addresshash, and ownerentropy
            byte[] passpoint = BitcoinEncryptedSecretEC.CalculatePassPoint(passfactor);
            byte[] derived = BitcoinEncryptedSecretEC.CalculateDecryptionKey(passpoint, AddressHash, OwnerEntropy);

            //Decrypt encryptedpointb to yield pointb
            var pointbprefix = EncryptedPointB[0];
            pointbprefix = (byte)(pointbprefix ^ (byte)(derived[63] & (byte)0x01));

            //Optional since ArithmeticException will catch it, but it saves some times
            if(pointbprefix != 0x02 && pointbprefix != 0x03)
                return false;
            var pointb = BitcoinEncryptedSecret.DecryptKey(EncryptedPointB.Skip(1).ToArray(), derived);
            pointb = new byte[] { pointbprefix }.Concat(pointb).ToArray();

            //4.ECMultiply pointb by passfactor. Use the resulting EC point as a public key
            var curve = ECKey.CreateCurve();
            ECPoint pointbec = null;
            try
            {
                pointbec = curve.Curve.DecodePoint(pointb);
            }
            catch(ArithmeticException)
            {
                return false;
            }
            PubKey pubkey = new PubKey(pointbec.Multiply(new BigInteger(1, passfactor)).GetEncoded());

            //and hash it into address using either compressed or uncompressed public key methodology as specifid in flagbyte.
            pubkey = IsCompressed ? pubkey.Compress() : pubkey.Decompress();

            var actualhash = BitcoinEncryptedSecretEC.HashAddress(pubkey.GetAddress(Network));
            var expectedhash = BitcoinEncryptedSecretEC.HashAddress(expectedAddress);

            return Utils.ArrayEqual(actualhash, expectedhash);
        }
 public Script GenerateScriptPubKey(int sigCount, PubKey[] keys)
 {
     List<Op> ops = new List<Op>();
     var push = Op.GetPushOp(sigCount);
     if(!push.IsSmallUInt)
         throw new ArgumentOutOfRangeException("sigCount should be less or equal to 16");
     ops.Add(push);
     var keyCount = Op.GetPushOp(keys.Length);
     if(!keyCount.IsSmallUInt)
         throw new ArgumentOutOfRangeException("key count should be less or equal to 16");
     foreach(var key in keys)
     {
         ops.Add(Op.GetPushOp(key.ToBytes()));
     }
     ops.Add(keyCount);
     ops.Add(OpcodeType.OP_CHECKMULTISIG);
     return new Script(ops.ToArray());
 }
Beispiel #14
0
		public Block CreateNextBlockWithCoinbase(PubKey pubkey, Money value, DateTimeOffset now)
		{
			Block block = new Block();
			block.Header.Nonce = RandomUtils.GetUInt32();
			block.Header.HashPrevBlock = this.GetHash();
			block.Header.BlockTime = now;
			var tx = block.AddTransaction(new Transaction());
			tx.AddInput(new TxIn()
			{
				ScriptSig = new Script(Op.GetPushOp(RandomUtils.GetBytes(30)))
			});
			tx.Outputs.Add(new TxOut()
			{
				Value = value,
				ScriptPubKey = PayToPubkeyHashTemplate.Instance.GenerateScriptPubKey(pubkey)
			});
			return block;
		}
Beispiel #15
0
 public PubKey UncoverReceiver(Key scan, PubKey ephem)
 {
     return(Uncover(scan, ephem));
 }
Beispiel #16
0
 public BitcoinStealthAddress CreateStealthAddress(PubKey scanKey, Network network)
 {
     return(new BitcoinStealthAddress(scanKey, new PubKey[] { this }, 1, null, network));
 }
Beispiel #17
0
        public bool VerifyMessage(string message, string signature)
        {
            var key = PubKey.RecoverFromMessage(message, signature);

            return(key.ID == ID);
        }
Beispiel #18
0
 public PubKey UncoverSender(Key ephem, PubKey scan)
 {
     return(Uncover(ephem, scan));
 }
Beispiel #19
0
 public static Script PayToPubkey(PubKey pubkey)
 {
     return(PayToPubkeyTemplate.Instance.GenerateScriptPubKey(pubkey));
 }
 private bool CheckWitScriptCore(WitScript witScript)
 {
     return(witScript.PushCount == 2 &&
            ((witScript[0].Length == 1 && witScript[0][0] == 0) || (TransactionSignature.IsValid(witScript[0], ScriptVerify.None))) &&
            PubKey.Check(witScript[1], false));
 }
Beispiel #21
0
 /// <summary>
 /// Add keypath information to this PSBT for each input or output involving it
 /// </summary>
 /// <param name="pubkey">The public key which need to sign</param>
 /// <param name="rootedKeyPath">The keypath to this public key</param>
 /// <returns>This PSBT</returns>
 public PSBT AddKeyPath(PubKey pubkey, RootedKeyPath rootedKeyPath)
 {
     return(AddKeyPath(pubkey, rootedKeyPath, null));
 }
Beispiel #22
0
 public Key GetKey(PubKey pubKey)
 {
     return _Keys.FirstOrDefault(k => k.PubKey == pubKey);
 }
Beispiel #23
0
 private Key FindKey(TransactionSigningContext ctx, PubKey pubKey)
 {
     return(_Keys
            .Concat(ctx.AdditionalKeys)
            .FirstOrDefault(k => k.PubKey == pubKey));
 }
Beispiel #24
0
 public static Script PayToPubkey(PubKey pubkey)
 {
     return new PayToPubkeyTemplate().GenerateScriptPubKey(pubkey);
 }
        public static bool VerifyMessage(this BitcoinWitPubKeyAddress address, uint256 messageHash, byte[] signature)
        {
            PubKey pubKey = PubKey.RecoverCompact(messageHash, signature);

            return(pubKey.WitHash == address.Hash);
        }
Beispiel #26
0
        public EncryptedKeyResult GenerateEncryptedSecret(bool isCompressed = true, byte[] seedb = null)
        {
            //Set flagbyte.
            byte flagByte = 0;

            //Turn on bit 0x20 if the Bitcoin address will be formed by hashing the compressed public key
            flagByte |= isCompressed ? (byte)0x20 : (byte)0x00;
            flagByte |= LotSequence != null ? (byte)0x04 : (byte)0x00;

            //Generate 24 random bytes, call this seedb. Take SHA256(SHA256(seedb)) to yield 32 bytes, call this factorb.
            seedb = seedb ?? RandomUtils.GetBytes(24);

            var factorb = Hashes.Hash256(seedb).ToBytes();

            //ECMultiply passpoint by factorb.
            var curve     = ECKey.Secp256k1;
            var passpoint = curve.Curve.DecodePoint(Passpoint);
            var pubPoint  = passpoint.Multiply(new BigInteger(1, factorb));

            //Use the resulting EC point as a public key
            var pubKey = new PubKey(pubPoint.GetEncoded());

            //and hash it into a Bitcoin address using either compressed or uncompressed public key
            //This is the generated Bitcoin address, call it generatedaddress.
            pubKey = isCompressed ? pubKey.Compress() : pubKey.Decompress();

            //call it generatedaddress.
            var generatedaddress = pubKey.GetAddress(ScriptPubKeyType.Legacy, Network);

            //Take the first four bytes of SHA256(SHA256(generatedaddress)) and call it addresshash.
            var addresshash = BitcoinEncryptedSecretEC.HashAddress(generatedaddress);

            //Derive a second key from passpoint using scrypt
            //salt is addresshash + ownerentropy
            var derived = BitcoinEncryptedSecretEC.CalculateDecryptionKey(Passpoint, addresshash, OwnerEntropy);

            //Now we will encrypt seedb.
            var encrypted = BitcoinEncryptedSecret.EncryptSeed
                                (seedb,
                                derived);

            //0x01 0x43 + flagbyte + addresshash + ownerentropy + encryptedpart1[0...7] + encryptedpart2 which totals 39 bytes
            var bytes =
                new[] { flagByte }
            .Concat(addresshash)
            .Concat(this.OwnerEntropy)
            .Concat(encrypted.Take(8).ToArray())
            .Concat(encrypted.Skip(16).ToArray())
            .ToArray();

            var encryptedSecret = new BitcoinEncryptedSecretEC(bytes, Network);

            return(new EncryptedKeyResult(encryptedSecret, generatedaddress, seedb, () =>
            {
                //ECMultiply factorb by G, call the result pointb. The result is 33 bytes.
                var pointb = new Key(factorb).PubKey.ToBytes();
                //The first byte is 0x02 or 0x03. XOR it by (derivedhalf2[31] & 0x01), call the resulting byte pointbprefix.
                var pointbprefix = (byte)(pointb[0] ^ (byte)(derived[63] & 0x01));
                var pointbx = BitcoinEncryptedSecret.EncryptKey(pointb.Skip(1).ToArray(), derived);
                var encryptedpointb = new byte[] { pointbprefix }.Concat(pointbx).ToArray();

                var confirmBytes =
                    Network.GetVersionBytes(Base58Type.CONFIRMATION_CODE, true)
                    .Concat(new[] { flagByte })
                    .Concat(addresshash)
                    .Concat(OwnerEntropy)
                    .Concat(encryptedpointb)
                    .ToArray();

                return new BitcoinConfirmationCode(Network.NetworkStringParser.GetBase58CheckEncoder().EncodeData(confirmBytes), Network);
            }));
        }
        public static uint256 BlindScript(this Requester requester, PubKey signerPubKey, PubKey RPubKey, Script script)
        {
            var msg = new uint256(Hashes.SHA256(script.ToBytes()));

            return(requester.BlindMessage(msg, RPubKey, signerPubKey));
        }
Beispiel #28
0
 Script Decompress(uint nSize, byte[] data)
 {
     switch(nSize)
     {
         case 0x00:
             return new Script(OpcodeType.OP_DUP, OpcodeType.OP_HASH160, Op.GetPushOp(data.Take(20).ToArray()), OpcodeType.OP_EQUALVERIFY, OpcodeType.OP_CHECKSIG);
         case 0x01:
             return new Script(OpcodeType.OP_HASH160, Op.GetPushOp(data.Take(20).ToArray()), OpcodeType.OP_EQUAL);
         case 0x02:
         case 0x03:
             return new Script(Op.GetPushOp(new byte[] { (byte)nSize }.Concat(data.Take(32)).ToArray()), OpcodeType.OP_CHECKSIG);
         case 0x04:
         case 0x05:
             byte[] vch = new byte[33];
             vch[0] = (byte)(nSize - 2);
             Array.Copy(data, vch, 32);
             PubKey pubkey = new PubKey(vch);
             pubkey = pubkey.Decompress();
             return new Script(Op.GetPushOp(pubkey.ToBytes()), OpcodeType.OP_CHECKSIG);
     }
     return null;
 }
Beispiel #29
0
 public override int GetHashCode()
 {
     return(PubKey.GetHashCode());
 }
Beispiel #30
0
 public BitcoinStealthAddress(PubKey scanKey, PubKey[] pubKeys, int signatureCount, BitField bitfield, Network network)
     : base(GenerateBytes(scanKey, pubKeys, bitfield, signatureCount), network)
 {
 }
Beispiel #31
0
        internal PSBTOutput(BitcoinStream stream, PSBT parent, uint index, TxOut txOut) : base(parent)
        {
            if (txOut == null)
            {
                throw new ArgumentNullException(nameof(txOut));
            }
            if (parent == null)
            {
                throw new ArgumentNullException(nameof(parent));
            }

            TxOut = txOut;
            Index = index;

            byte[] k = new byte[0];
            byte[] v = new byte[0];
            try
            {
                stream.ReadWriteAsVarString(ref k);
            }
            catch (EndOfStreamException e)
            {
                throw new FormatException("Invalid PSBTOutput. Could not read key", e);
            }
            while (k.Length != 0)
            {
                try
                {
                    stream.ReadWriteAsVarString(ref v);
                }
                catch (EndOfStreamException e)
                {
                    throw new FormatException("Invalid PSBTOutput. Could not read value", e);
                }
                switch (k.First())
                {
                case PSBTConstants.PSBT_OUT_REDEEMSCRIPT:
                    if (k.Length != 1)
                    {
                        throw new FormatException("Invalid PSBTOutput. Contains illegal value in key for redeem script");
                    }
                    if (redeem_script != null)
                    {
                        throw new FormatException("Invalid PSBTOutput, duplicate key for redeem_script");
                    }
                    redeem_script = Script.FromBytesUnsafe(v);
                    break;

                case PSBTConstants.PSBT_OUT_WITNESSSCRIPT:
                    if (k.Length != 1)
                    {
                        throw new FormatException("Invalid PSBTOutput. Contains illegal value in key for witness script");
                    }
                    if (witness_script != null)
                    {
                        throw new FormatException("Invalid PSBTOutput, duplicate key for redeem_script");
                    }
                    witness_script = Script.FromBytesUnsafe(v);
                    break;

                case PSBTConstants.PSBT_OUT_BIP32_DERIVATION:
                    var pubkey2 = new PubKey(k.Skip(1).ToArray());
                    if (hd_keypaths.ContainsKey(pubkey2))
                    {
                        throw new FormatException("Invalid PSBTOutput, duplicate key for hd_keypaths");
                    }
                    KeyPath path = KeyPath.FromBytes(v.Skip(4).ToArray());
                    hd_keypaths.Add(pubkey2, new RootedKeyPath(new HDFingerprint(v.Take(4).ToArray()), path));
                    break;

                default:
                    if (unknown.ContainsKey(k))
                    {
                        throw new FormatException("Invalid PSBTInput, duplicate key for unknown value");
                    }
                    unknown.Add(k, v);
                    break;
                }
                stream.ReadWriteAsVarString(ref k);
            }
        }
Beispiel #32
0
 public BitcoinStealthAddress CreateStealthAddress(PubKey scanKey, Network network)
 {
     return new BitcoinStealthAddress(scanKey, new PubKey[] { this }, 1, null, network);
 }
Beispiel #33
0
 public Block CreateNextBlockWithCoinbase(PubKey pubkey, Money value)
 {
     return(this.CreateNextBlockWithCoinbase(pubkey, value, DateTimeOffset.UtcNow));
 }
Beispiel #34
0
 public PubKey UncoverReceiver(Key scan, PubKey ephem)
 {
     return Uncover(scan, ephem);
 }
Beispiel #35
0
 public override void AddKeyPath(HDFingerprint fingerprint, PubKey key, KeyPath path)
 {
     base.AddKeyPath(fingerprint, key, path);
     TrySlimOutput();
 }
Beispiel #36
0
 internal static byte[] GetStealthSharedSecret(Key priv, PubKey pub)
 {
     var curve = ECKey.CreateCurve();
     var pubec = curve.Curve.DecodePoint(pub.ToBytes());
     var p = pubec.Multiply(new BigInteger(1, priv.ToBytes()));
     var pBytes = new PubKey(p.GetEncoded()).Compress().ToBytes();
     var hash = Hashes.SHA256(pBytes);
     return hash;
 }
Beispiel #37
0
        internal PSBTInput(BitcoinStream stream, PSBT parent, uint index, TxIn input) : base(parent)
        {
            TxIn              = input;
            Index             = index;
            originalScriptSig = TxIn.ScriptSig ?? Script.Empty;
            originalWitScript = TxIn.WitScript ?? WitScript.Empty;
            byte[] k = new byte[0];
            byte[] v = new byte[0];
            try
            {
                stream.ReadWriteAsVarString(ref k);
            }
            catch (EndOfStreamException e)
            {
                throw new FormatException("Invalid PSBTInput. Failed to Parse key.", e);
            }
            while (k.Length != 0)
            {
                try
                {
                    stream.ReadWriteAsVarString(ref v);
                }
                catch (EndOfStreamException e)
                {
                    throw new FormatException("Invalid PSBTInput. Failed to parse key.", e);
                }
                switch (k.First())
                {
                case PSBTConstants.PSBT_IN_NON_WITNESS_UTXO:
                    if (k.Length != 1)
                    {
                        throw new FormatException("Invalid PSBTInput. Contains illegal value in key for NonWitnessUTXO");
                    }
                    if (non_witness_utxo != null)
                    {
                        throw new FormatException("Invalid PSBTInput. Duplicate non_witness_utxo");
                    }
                    non_witness_utxo = this.GetConsensusFactory().CreateTransaction();
                    non_witness_utxo.FromBytes(v);
                    break;

                case PSBTConstants.PSBT_IN_WITNESS_UTXO:
                    if (k.Length != 1)
                    {
                        throw new FormatException("Invalid PSBTInput. Contains illegal value in key for WitnessUTXO");
                    }
                    if (witness_utxo != null)
                    {
                        throw new FormatException("Invalid PSBTInput. Duplicate witness_utxo");
                    }
                    if (this.GetConsensusFactory().TryCreateNew <TxOut>(out var txout))
                    {
                        witness_utxo = txout;
                    }
                    else
                    {
                        witness_utxo = new TxOut();
                    }
                    witness_utxo.FromBytes(v);
                    break;

                case PSBTConstants.PSBT_IN_PARTIAL_SIG:
                    var pubkey = new PubKey(k.Skip(1).ToArray());
                    if (partial_sigs.ContainsKey(pubkey))
                    {
                        throw new FormatException("Invalid PSBTInput. Duplicate key for partial_sigs");
                    }
                    partial_sigs.Add(pubkey, new TransactionSignature(v));
                    break;

                case PSBTConstants.PSBT_IN_SIGHASH:
                    if (k.Length != 1)
                    {
                        throw new FormatException("Invalid PSBTInput. Contains illegal value in key for SigHash type");
                    }
                    if (!(sighash_type is null))
                    {
                        throw new FormatException("Invalid PSBTInput. Duplicate key for sighash_type");
                    }
                    if (v.Length != 4)
                    {
                        throw new FormatException("Invalid PSBTInput. SigHash Type is not 4 byte");
                    }
                    var value = Utils.ToUInt32(v, 0, true);
                    if (!Enum.IsDefined(typeof(SigHash), value))
                    {
                        throw new FormatException($"Invalid PSBTInput Unknown SigHash Type {value}");
                    }
                    sighash_type = (SigHash)value;
                    break;

                case PSBTConstants.PSBT_IN_REDEEMSCRIPT:
                    if (k.Length != 1)
                    {
                        throw new FormatException("Invalid PSBTInput. Contains illegal value in key for redeem script");
                    }
                    if (redeem_script != null)
                    {
                        throw new FormatException("Invalid PSBTInput. Duplicate key for redeem_script");
                    }
                    redeem_script = Script.FromBytesUnsafe(v);
                    break;

                case PSBTConstants.PSBT_IN_WITNESSSCRIPT:
                    if (k.Length != 1)
                    {
                        throw new FormatException("Invalid PSBTInput. Contains illegal value in key for witness script");
                    }
                    if (witness_script != null)
                    {
                        throw new FormatException("Invalid PSBTInput. Duplicate key for redeem_script");
                    }
                    witness_script = Script.FromBytesUnsafe(v);
                    break;

                case PSBTConstants.PSBT_IN_BIP32_DERIVATION:
                    var pubkey2 = new PubKey(k.Skip(1).ToArray());
                    if (hd_keypaths.ContainsKey(pubkey2))
                    {
                        throw new FormatException("Invalid PSBTInput. Duplicate key for hd_keypaths");
                    }
                    var     masterFingerPrint = new HDFingerprint(v.Take(4).ToArray());
                    KeyPath path = KeyPath.FromBytes(v.Skip(4).ToArray());
                    hd_keypaths.Add(pubkey2, Tuple.Create(masterFingerPrint, path));
                    break;

                case PSBTConstants.PSBT_IN_SCRIPTSIG:
                    if (k.Length != 1)
                    {
                        throw new FormatException("Invalid PSBTInput. Contains illegal value in key for final scriptsig");
                    }
                    if (final_script_sig != null)
                    {
                        throw new FormatException("Invalid PSBTInput. Duplicate key for final_script_sig");
                    }
                    final_script_sig = Script.FromBytesUnsafe(v);
                    break;

                case PSBTConstants.PSBT_IN_SCRIPTWITNESS:
                    if (k.Length != 1)
                    {
                        throw new FormatException("Invalid PSBTInput. Contains illegal value in key for final script witness");
                    }
                    if (final_script_witness != null)
                    {
                        throw new FormatException("Invalid PSBTInput. Duplicate key for final_script_witness");
                    }
                    final_script_witness = new WitScript(v);
                    break;

                default:
                    if (unknown.ContainsKey(k))
                    {
                        throw new FormatException("Invalid PSBTInput. Duplicate key for unknown value");
                    }
                    unknown.Add(k, v);
                    break;
                }
                stream.ReadWriteAsVarString(ref k);
            }
        }
Beispiel #38
0
 public Block CreateNextBlockWithCoinbase(PubKey pubkey, Money value, DateTimeOffset now)
 {
     return(CreateNextBlockWithCoinbase(pubkey, value, now, Consensus.Main.ConsensusFactory));
 }
Beispiel #39
0
        public ExtPubKey Derive(uint index)
        {
            var childPubKey = pubkey.Derivate(this.vchChainCode, index, out var chainCode);
            var result      = new ExtPubKey(childPubKey, chainCode, (byte)(nDepth + 1), PubKey.GetHDFingerPrint(), index);

            return(result);
        }
Beispiel #40
0
 public Block CreateNextBlockWithCoinbase(PubKey pubkey, Money value, ConsensusFactory consensusFactory)
 {
     return(CreateNextBlockWithCoinbase(pubkey, value, DateTimeOffset.UtcNow, consensusFactory));
 }
Beispiel #41
0
 public bool IsTo(PubKey pubkey)
 {
     return IsTo(pubkey.ID);
 }
Beispiel #42
0
 public override void AddKeyPath(PubKey key, RootedKeyPath rootedKeyPath)
 {
     base.AddKeyPath(key, rootedKeyPath);
     TrySlimUTXO();
 }
Beispiel #43
0
		public Key Uncover(Key scan, PubKey ephem)
		{
			var curve = ECKey.Secp256k1;
			var priv = new BigInteger(1, PubKey.GetStealthSharedSecret(scan, ephem))
							.Add(new BigInteger(1, this.ToBytes()))
							.Mod(curve.N)
							.ToByteArrayUnsigned();

			if(priv.Length < 32)
				priv = new byte[32 - priv.Length].Concat(priv).ToArray();

			var key = new Key(priv, fCompressedIn: this.IsCompressed);
			return key;
		}
 public Script GenerateScriptSig(TransactionSignature signature, PubKey publicKey)
 {
     if(signature == null)
         throw new ArgumentNullException("signature");
     if(publicKey == null)
         throw new ArgumentNullException("publicKey");
     return new Script(
         Op.GetPushOp(signature.ToBytes()),
         Op.GetPushOp(publicKey.ToBytes())
         );
 }
		public Script GenerateScriptPubKey(PubKey pubKey)
		{
			if(pubKey == null)
				throw new ArgumentNullException("pubKey");
			return GenerateScriptPubKey(pubKey.WitHash);
		}
Beispiel #46
0
		public Block CreateNextBlockWithCoinbase(PubKey pubkey, Money value)
		{
			return CreateNextBlockWithCoinbase(pubkey, value, DateTimeOffset.UtcNow);
		}
Beispiel #47
0
        public bool IsFrom(PubKey pubKey)
        {
            var result = PayToPubkeyHashTemplate.Instance.ExtractScriptSigParameters(ScriptSig);

            return(result != null && result.PublicKey == pubKey);
        }
Beispiel #48
0
		public PubKey[] Uncover(PubKey[] spendPubKeys, Key scanKey)
		{
			var pubKeys = new PubKey[spendPubKeys.Length];
			for(int i = 0 ; i < pubKeys.Length ; i++)
			{
				pubKeys[i] = spendPubKeys[i].UncoverReceiver(scanKey, StealthMetadata.EphemKey);
			}
			return pubKeys;
		}
		public EncryptedKeyResult GenerateEncryptedSecret(bool isCompressed = true, byte[] seedb = null)
		{
			//Set flagbyte.
			byte flagByte = 0;
			//Turn on bit 0x20 if the Bitcoin address will be formed by hashing the compressed public key
			flagByte |= isCompressed ? (byte)0x20 : (byte)0x00;
			flagByte |= LotSequence != null ? (byte)0x04 : (byte)0x00;

			//Generate 24 random bytes, call this seedb. Take SHA256(SHA256(seedb)) to yield 32 bytes, call this factorb.
			seedb = seedb ?? RandomUtils.GetBytes(24);

			var factorb = Hashes.Hash256(seedb).ToBytes();

			//ECMultiply passpoint by factorb.
			var curve = ECKey.Secp256k1;
			var passpoint = curve.Curve.DecodePoint(Passpoint);
			var pubPoint = passpoint.Multiply(new BigInteger(1, factorb));

			//Use the resulting EC point as a public key
			var pubKey = new PubKey(pubPoint.GetEncoded());

			//and hash it into a Bitcoin address using either compressed or uncompressed public key
			//This is the generated Bitcoin address, call it generatedaddress.
			pubKey = isCompressed ? pubKey.Compress() : pubKey.Decompress();

			//call it generatedaddress.
			var generatedaddress = pubKey.GetAddress(Network);

			//Take the first four bytes of SHA256(SHA256(generatedaddress)) and call it addresshash.
			var addresshash = BitcoinEncryptedSecretEC.HashAddress(generatedaddress);

			//Derive a second key from passpoint using scrypt
			//salt is addresshash + ownerentropy
			var derived = BitcoinEncryptedSecretEC.CalculateDecryptionKey(Passpoint, addresshash, OwnerEntropy);

			//Now we will encrypt seedb.
			var encrypted = BitcoinEncryptedSecret.EncryptSeed
							(seedb,
							derived);

			//0x01 0x43 + flagbyte + addresshash + ownerentropy + encryptedpart1[0...7] + encryptedpart2 which totals 39 bytes
			var bytes =
				new[] { flagByte }
				.Concat(addresshash)
				.Concat(this.OwnerEntropy)
				.Concat(encrypted.Take(8).ToArray())
				.Concat(encrypted.Skip(16).ToArray())
				.ToArray();

			var encryptedSecret = new BitcoinEncryptedSecretEC(bytes, Network);

			return new EncryptedKeyResult(encryptedSecret, generatedaddress, seedb, () =>
			{
				//ECMultiply factorb by G, call the result pointb. The result is 33 bytes.
				var pointb = new Key(factorb).PubKey.ToBytes();
				//The first byte is 0x02 or 0x03. XOR it by (derivedhalf2[31] & 0x01), call the resulting byte pointbprefix.
				var pointbprefix = (byte)(pointb[0] ^ (byte)(derived[63] & 0x01));
				var pointbx = BitcoinEncryptedSecret.EncryptKey(pointb.Skip(1).ToArray(), derived);
				var encryptedpointb = new byte[] { pointbprefix }.Concat(pointbx).ToArray();

				var confirmBytes =
					Network.GetVersionBytes(Base58Type.CONFIRMATION_CODE)
					.Concat(new[] { flagByte })
					.Concat(addresshash)
					.Concat(OwnerEntropy)
					.Concat(encryptedpointb)
					.ToArray();

				return new BitcoinConfirmationCode(Encoders.Base58Check.EncodeData(confirmBytes), Network);
			});
		}
Beispiel #50
0
 public bool IsFrom(PubKey pubKey)
 {
     var template = new PayToPubkeyHashTemplate();
     var result = template.ExtractScriptSigParameters(ScriptSig);
     return result != null && result.PublicKey == pubKey;
 }
Beispiel #51
0
 public Script GenerateScriptPubKey(PubKey pubkey)
 {
     return(GenerateScriptPubKey(pubkey.ToBytes(true)));
 }
Beispiel #52
0
		public static Script PayToPubkey(PubKey pubkey)
		{
			return PayToPubkeyTemplate.Instance.GenerateScriptPubKey(pubkey);
		}
 private static byte[] GenerateBytes(PubKey scanKey, PubKey[] pubKeys, BitField bitField, int signatureCount)
 {
     MemoryStream ms = new MemoryStream();
     ms.WriteByte(0); //Options
     ms.Write(scanKey.Compress().ToBytes(), 0, 33);
     ms.WriteByte((byte)pubKeys.Length);
     foreach(var key in pubKeys)
     {
         ms.Write(key.Compress().ToBytes(), 0, 33);
     }
     ms.WriteByte((byte)signatureCount);
     if(bitField == null)
         ms.Write(new byte[] { 0 }, 0, 1);
     else
     {
         ms.WriteByte((byte)bitField.BitCount);
         var raw = bitField.GetRawForm();
         ms.Write(raw, 0, raw.Length);
     }
     return ms.ToArray();
 }
		public Script GenerateScriptPubKey(PubKey pubkey)
		{
			return new Script(
					Op.GetPushOp(pubkey.ToBytes()),
					OpcodeType.OP_CHECKSIG
				);
		}
 public BitcoinStealthAddress(PubKey scanKey, PubKey[] pubKeys, int signatureCount, BitField bitfield, Network network)
     : base(GenerateBytes(scanKey, pubKeys, bitfield, signatureCount), network)
 {
 }
		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())
				);
		}
 protected override BitcoinBlindedAddress CreateBlindedAddressCore(PubKey blinded)
 {
     return(this);
 }