コード例 #1
0
ファイル: Utils.cs プロジェクト: tohidkazemi/NBitcoin
        internal static Secp256k1.SecpECDSASignature Sign(this Secp256k1.ECPrivKey key, uint256 h, bool enforceLowR, out int recid)
        {
            Span <byte> hash = stackalloc byte[32];

            h.ToBytes(hash);
            byte[] extra_entropy = null;
            Secp256k1.RFC6979NonceFunction nonceFunction = null;
            Span <byte> vchSig = stackalloc byte[Secp256k1.SecpECDSASignature.MaxLength];

            Secp256k1.SecpECDSASignature sig;
            uint counter = 0;
            bool ret     = key.TrySignECDSA(hash, null, out recid, out sig);

            // Grind for low R
            while (ret && sig.r.IsHigh && enforceLowR)
            {
                if (extra_entropy == null || nonceFunction == null)
                {
                    extra_entropy = new byte[32];
                    nonceFunction = new Secp256k1.RFC6979NonceFunction(extra_entropy);
                }
                Utils.ToBytes(++counter, true, extra_entropy.AsSpan());
                ret = key.TrySignECDSA(hash, nonceFunction, out recid, out sig);
            }
            return(sig);
        }
コード例 #2
0
        public byte[] ToBytes(bool lendian = true)
        {
            var arr = new byte[WIDTH_BYTE];

            Buffer.BlockCopy(Utils.ToBytes(pn0, true), 0, arr, 4 * 0, 4);
            Buffer.BlockCopy(Utils.ToBytes(pn1, true), 0, arr, 4 * 1, 4);
            Buffer.BlockCopy(Utils.ToBytes(pn2, true), 0, arr, 4 * 2, 4);
            Buffer.BlockCopy(Utils.ToBytes(pn3, true), 0, arr, 4 * 3, 4);
            Buffer.BlockCopy(Utils.ToBytes(pn4, true), 0, arr, 4 * 4, 4);
            Buffer.BlockCopy(Utils.ToBytes(pn5, true), 0, arr, 4 * 5, 4);
            Buffer.BlockCopy(Utils.ToBytes(pn6, true), 0, arr, 4 * 6, 4);
            Buffer.BlockCopy(Utils.ToBytes(pn7, true), 0, arr, 4 * 7, 4);
            Buffer.BlockCopy(Utils.ToBytes(pn8, true), 0, arr, 4 * 8, 4);
            Buffer.BlockCopy(Utils.ToBytes(pn9, true), 0, arr, 4 * 9, 4);
            Buffer.BlockCopy(Utils.ToBytes(pn10, true), 0, arr, 4 * 10, 4);
            Buffer.BlockCopy(Utils.ToBytes(pn11, true), 0, arr, 4 * 11, 4);
            Buffer.BlockCopy(Utils.ToBytes(pn12, true), 0, arr, 4 * 12, 4);
            Buffer.BlockCopy(Utils.ToBytes(pn13, true), 0, arr, 4 * 13, 4);
            Buffer.BlockCopy(Utils.ToBytes(pn14, true), 0, arr, 4 * 14, 4);
            Buffer.BlockCopy(Utils.ToBytes(pn15, true), 0, arr, 4 * 15, 4);
            if (!lendian)
            {
                Array.Reverse(arr);
            }
            return(arr);
        }
コード例 #3
0
        public void ToBytes(Span <byte> output, bool lendian = true)
        {
            if (output.Length < WIDTH_BYTE)
            {
                throw new ArgumentException(message: $"The array should be at least of size {WIDTH_BYTE}", paramName: nameof(output));
            }

            var initial = output;

            Utils.ToBytes(pn0, true, output);
            output = output.Slice(4);
            Utils.ToBytes(pn1, true, output);
            output = output.Slice(4);
            Utils.ToBytes(pn2, true, output);
            output = output.Slice(4);
            Utils.ToBytes(pn3, true, output);
            output = output.Slice(4);
            Utils.ToBytes(pn4, true, output);
            output = output.Slice(4);
            Utils.ToBytes(pn5, true, output);
            output = output.Slice(4);
            Utils.ToBytes(pn6, true, output);
            output = output.Slice(4);
            Utils.ToBytes(pn7, true, output);

            if (!lendian)
            {
                initial.Reverse();
            }
        }
コード例 #4
0
 public void ToBytes(byte[] output)
 {
     Buffer.BlockCopy(Utils.ToBytes(pn0, true), 0, output, 4 * 0, 4);
     Buffer.BlockCopy(Utils.ToBytes(pn1, true), 0, output, 4 * 1, 4);
     Buffer.BlockCopy(Utils.ToBytes(pn2, true), 0, output, 4 * 2, 4);
     Buffer.BlockCopy(Utils.ToBytes(pn3, true), 0, output, 4 * 3, 4);
     Buffer.BlockCopy(Utils.ToBytes(pn4, true), 0, output, 4 * 4, 4);
     Buffer.BlockCopy(Utils.ToBytes(pn5, true), 0, output, 4 * 5, 4);
     Buffer.BlockCopy(Utils.ToBytes(pn6, true), 0, output, 4 * 6, 4);
     Buffer.BlockCopy(Utils.ToBytes(pn7, true), 0, output, 4 * 7, 4);
 }
コード例 #5
0
        public StealthMetadata(Key ephemKey, uint nonce)
        {
            var data = new MemoryStream();

            data.WriteByte(6);
            var b = Utils.ToBytes(nonce, true);

            data.Write(b, 0, b.Length);
            data.Write(ephemKey.PubKey.Compress().ToBytes(), 0, 33);
            Fill(this, new Script(OpcodeType.OP_RETURN, Op.GetPushOp(data.ToArray())));
        }
コード例 #6
0
        public byte[] ToBytes(bool lendian = true)
        {
            var arr = new byte[WIDTH_BYTE];

            for (int i = 0; i < WIDTH; i++)
            {
                Buffer.BlockCopy(Utils.ToBytes(pn[i], true), 0, arr, 4 * i, 4);
            }
            if (!lendian)
            {
                Array.Reverse(arr);
            }
            return(arr);
        }
コード例 #7
0
ファイル: UInt256.cs プロジェクト: neblidex/neblidex-android
        public byte[] ToBytes(bool lendian = true)
        {
            var arr = new byte[WIDTH_BYTE];

            Buffer.BlockCopy(Utils.ToBytes(pn0, true), 0, arr, 4 * 0, 4);
            Buffer.BlockCopy(Utils.ToBytes(pn1, true), 0, arr, 4 * 1, 4);
            Buffer.BlockCopy(Utils.ToBytes(pn2, true), 0, arr, 4 * 2, 4);
            Buffer.BlockCopy(Utils.ToBytes(pn3, true), 0, arr, 4 * 3, 4);
            Buffer.BlockCopy(Utils.ToBytes(pn4, true), 0, arr, 4 * 4, 4);
            if (!lendian)
            {
                Array.Reverse(arr);
            }
            return(arr);
        }
コード例 #8
0
ファイル: ExtPubKey.cs プロジェクト: MichalisN/NBitcoin
        public byte[] ToBytes()
        {
            var b = new byte[Length];
            int i = 0;

            b[i++] = nDepth;
            Array.Copy(parentFingerprint.ToBytes(), 0, b, i, 4);
            i += 4;
            Array.Copy(Utils.ToBytes(nChild, false), 0, b, i, 4);
            i += 4;
            Array.Copy(vchChainCode, 0, b, i, 32);
            i += 32;
            Array.Copy(pubkey.ToBytes(), 0, b, i, 33);
            return(b);
        }
コード例 #9
0
        public void ToBytes(Span <byte> output, bool lendian = true)
        {
            if (output.Length < WIDTH_BYTE)
            {
                throw new ArgumentException(message: $"The array should be at least of size {WIDTH_BYTE}", paramName: nameof(output));
            }

            if (BitConverter.IsLittleEndian)
            {
                if (lendian)
                {
                    var ulongOutput = MemoryMarshal.Cast <byte, ulong>(output);
                    ulongOutput[0] = pn0;
                    ulongOutput[1] = pn1;
                    ulongOutput[2] = pn2;
                    ulongOutput[3] = pn3;
                }
                else
                {
                    Span <ulong> temp = stackalloc ulong[4];
                    temp[0] = pn0;
                    temp[1] = pn1;
                    temp[2] = pn2;
                    temp[3] = pn3;
                    var tempBytes = MemoryMarshal.Cast <ulong, byte>(temp);
                    tempBytes.Reverse();
                    tempBytes.CopyTo(output);
                }
                return;
            }
            var initial = output;

            Utils.ToBytes(pn0, true, output);
            output = output.Slice(8);
            Utils.ToBytes(pn1, true, output);
            output = output.Slice(8);
            Utils.ToBytes(pn2, true, output);
            output = output.Slice(8);
            Utils.ToBytes(pn3, true, output);

            if (!lendian)
            {
                initial.Reverse();
            }
        }
コード例 #10
0
        public bool Match(uint value)
        {
            var data = Utils.ToBytes(value, true);

            if (data.Length * 8 < _BitCount)
            {
                return(false);
            }

            for (int i = 0; i < _Mask.Length; i++)
            {
                if ((data[i] & _Mask[i]) != (_Rawform[i] & _Mask[i]))
                {
                    return(false);
                }
            }
            return(true);
        }
コード例 #11
0
        /// <summary>
        /// Write this instance to the output
        /// </summary>
        /// <param name="output"></param>
        /// <param name="lendian"></param>
        public void ToBytes(byte[] output, bool lendian)
        {
#if HAS_SPAN
            ToBytes(output.AsSpan(), lendian);
#else
            if (lendian)
            {
                Buffer.BlockCopy(Utils.ToBytes(pn0, true), 0, output, 8 * 0, 8);
                Buffer.BlockCopy(Utils.ToBytes(pn1, true), 0, output, 8 * 1, 8);
                Buffer.BlockCopy(Utils.ToBytes(pn2, true), 0, output, 8 * 2, 8);
                Buffer.BlockCopy(Utils.ToBytes(pn3, true), 0, output, 8 * 3, 8);
            }
            else
            {
                Buffer.BlockCopy(Utils.ToBytes(pn3, false), 0, output, 8 * 0, 8);
                Buffer.BlockCopy(Utils.ToBytes(pn2, false), 0, output, 8 * 1, 8);
                Buffer.BlockCopy(Utils.ToBytes(pn1, false), 0, output, 8 * 2, 8);
                Buffer.BlockCopy(Utils.ToBytes(pn0, false), 0, output, 8 * 3, 8);
            }
#endif
        }
コード例 #12
0
        private static BitArray CalculateChecksum(uint256 blockId, int txIndex, int txOutIndex, Script scriptPubKey, int bitCount)
        {
            //All in little endian
            var hashed =
                blockId
                .ToBytes(true)
                .Concat(Utils.ToBytes((uint)txIndex, true))
                .Concat(Utils.ToBytes((uint)txOutIndex, true))
                .Concat(scriptPubKey.ToBytes(true))
                .ToArray();
            var      hash   = Hashes.Hash256(hashed);
            var      bytes  = hash.ToBytes(true);
            BitArray result = new BitArray(bitCount);

            for (int i = 0; i < bitCount; i++)
            {
                int byteIndex = i / 8;
                int bitIndex  = i % 8;
                result.Set(i, ((bytes[byteIndex] >> bitIndex) & 1) == 1);
            }
            return(result);
        }
コード例 #13
0
 public void ToBytes(Span <byte> output)
 {
     Utils.ToBytes(_Value, true, output);
 }
        public DerivationStrategyBase Parse(string str)
        {
            if (str == null)
            {
                throw new ArgumentNullException(nameof(str));
            }
            str = str.Trim();

            HashSet <string> hintedLabels = new HashSet <string>();

            var hintDestination = HintScriptPubKey?.GetDestination();

            if (hintDestination != null)
            {
                if (hintDestination is KeyId)
                {
                    hintedLabels.Add("legacy");
                }
                if (hintDestination is ScriptId)
                {
                    hintedLabels.Add("p2sh");
                }
            }
            else
            {
                if (Network.Consensus.SupportSegwit)
                {
                    hintedLabels.Add("p2sh");
                }
                else
                {
                    hintedLabels.Add("legacy");
                }
            }

            try {
                var result = new DerivationStrategyFactory(Network).Parse(str);
                return(FindMatch(hintedLabels, result));
            }
            catch {
            }

            Dictionary <uint, string[]> electrumMapping = new Dictionary <uint, string[]>();
            //Source https://github.com/spesmilo/electrum/blob/9edffd17542de5773e7284a8c8a2673c766bb3c3/lib/bitcoin.py
            var standard = 0x0488b21eU;

            electrumMapping.Add(standard, new[] { "legacy" });
            var p2wpkh_p2sh = 0x049d7cb2U;

            electrumMapping.Add(p2wpkh_p2sh, new string[] { "p2sh" });
            var p2wpkh = 0x4b24746U;

            electrumMapping.Add(p2wpkh, Array.Empty <string>());

            var parts = str.Split('-');

            for (int i = 0; i < parts.Length; i++)
            {
                if (IsLabel(parts[i]))
                {
                    hintedLabels.Add(parts[i].Substring(1, parts[i].Length - 2).ToLowerInvariant());
                    continue;
                }
                try {
                    var data = Network.GetBase58CheckEncoder().DecodeData(parts[i]);
                    if (data.Length < 4)
                    {
                        continue;
                    }
                    var prefix         = NU.ToUInt32(data, false);
                    var standardPrefix = NU.ToBytes(Network.NetworkType == NetworkType.Mainnet ? 0x0488b21eU : 0x043587cf, false);
                    for (int ii = 0; ii < 4; ii++)
                    {
                        data[ii] = standardPrefix[ii];
                    }

                    var derivationScheme = new BitcoinExtPubKey(Network.GetBase58CheckEncoder().EncodeData(data), Network).ToString();
                    electrumMapping.TryGetValue(prefix, out string[] labels);
                    if (labels != null)
                    {
                        foreach (var label in labels)
                        {
                            hintedLabels.Add(label.ToLowerInvariant());
                        }
                    }
                    parts[i] = derivationScheme;
                }
                catch { continue; }
            }

            if (hintDestination != null)
            {
                if (hintDestination is WitKeyId)
                {
                    hintedLabels.Remove("legacy");
                    hintedLabels.Remove("p2sh");
                }
            }

            str = string.Join('-', parts.Where(p => !IsLabel(p)));
            foreach (var label in hintedLabels)
            {
                str = $"{str}-[{label}]";
            }

            return(FindMatch(hintedLabels, new DerivationStrategyFactory(Network).Parse(str)));
        }
コード例 #15
0
 public BitField(uint encodedForm, int bitcount)
     : this(Utils.ToBytes(encodedForm, true), bitcount)
 {
 }
コード例 #16
0
 public byte[] ToBytes() =>
 Indexes.Count() == 0 ? new byte[0] : Indexes.Select(i => Utils.ToBytes(i, true)).Aggregate((a, b) => a.Concat(b)).ToArray();
コード例 #17
0
        public void Serialize(BitcoinStream stream)
        {
            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream));
            }
            // Write the utxo
            // If there is a non-witness utxo, then don't serialize the witness one.
            if (witness_utxo != null)
            {
                // key
                stream.ReadWriteAsVarInt(ref defaultKeyLen);
                var key = PSBTConstants.PSBT_IN_WITNESS_UTXO;
                stream.ReadWrite(ref key);

                // value
                var data = witness_utxo.ToBytes();
                stream.ReadWriteAsVarString(ref data);
            }

            if (non_witness_utxo != null)
            {
                // key
                stream.ReadWriteAsVarInt(ref defaultKeyLen);
                var key = PSBTConstants.PSBT_IN_NON_WITNESS_UTXO;
                stream.ReadWrite(ref key);
                // value
                byte[] data = non_witness_utxo.ToBytes();
                stream.ReadWriteAsVarString(ref data);
            }

            // Write the sighash type
            if (sighash_type > 0)
            {
                stream.ReadWriteAsVarInt(ref defaultKeyLen);
                var key = PSBTConstants.PSBT_IN_SIGHASH;
                stream.ReadWrite(ref key);
                var tmp = Utils.ToBytes((uint)sighash_type, true);
                stream.ReadWriteAsVarString(ref tmp);
            }

            // Write the redeem script
            if (redeem_script != null)
            {
                stream.ReadWriteAsVarInt(ref defaultKeyLen);
                var key = PSBTConstants.PSBT_IN_REDEEMSCRIPT;
                stream.ReadWrite(ref key);
                var value = redeem_script.ToBytes();
                stream.ReadWriteAsVarString(ref value);
            }

            // Write the witness script
            if (witness_script != null)
            {
                stream.ReadWriteAsVarInt(ref defaultKeyLen);
                var key = PSBTConstants.PSBT_IN_WITNESSSCRIPT;
                stream.ReadWrite(ref key);
                var value = witness_script.ToBytes();
                stream.ReadWriteAsVarString(ref value);
            }

            // Write any partial signatures
            foreach (var sig_pair in partial_sigs)
            {
                var key = new byte[] { PSBTConstants.PSBT_IN_PARTIAL_SIG }.Concat(sig_pair.Key.ToBytes());
                stream.ReadWriteAsVarString(ref key);
                var sig = sig_pair.Value.ToBytes();
                stream.ReadWriteAsVarString(ref sig);
            }

            // Write any hd keypaths
            foreach (var pathPair in hd_keypaths)
            {
                var key = new byte[] { PSBTConstants.PSBT_IN_BIP32_DERIVATION }.Concat(pathPair.Key.ToBytes());
                stream.ReadWriteAsVarString(ref key);
                var masterFingerPrint = pathPair.Value.MasterFingerprint;
                var path              = pathPair.Value.KeyPath.ToBytes();
                var pathInfo          = masterFingerPrint.ToBytes().Concat(path);
                stream.ReadWriteAsVarString(ref pathInfo);
            }

            // Write script sig
            if (final_script_sig != null)
            {
                stream.ReadWriteAsVarInt(ref defaultKeyLen);
                var key = PSBTConstants.PSBT_IN_SCRIPTSIG;
                stream.ReadWrite(ref key);
                byte[] value = final_script_sig.ToBytes();
                stream.ReadWriteAsVarString(ref value);
            }

            // write script witness
            if (final_script_witness != null)
            {
                stream.ReadWriteAsVarInt(ref defaultKeyLen);
                var key = PSBTConstants.PSBT_IN_SCRIPTWITNESS;
                stream.ReadWrite(ref key);
                var stack = final_script_witness.ToBytes();
                stream.ReadWriteAsVarString(ref stack);
            }

            // Write unknown things
            foreach (var entry in unknown)
            {
                var k = entry.Key;
                var v = entry.Value;
                stream.ReadWriteAsVarString(ref k);
                stream.ReadWriteAsVarString(ref v);
            }

            var sep = PSBTConstants.PSBT_SEPARATOR;

            stream.ReadWrite(ref sep);
        }
コード例 #18
0
 public byte[] ToBytes()
 {
     return(Utils.ToBytes(_Value, true));
 }