Exemplo n.º 1
0
        public static Block Load(byte[] bytes, ConsensusFactory consensusFactory)
        {
            if (bytes == null)
            {
                throw new ArgumentNullException(nameof(bytes));
            }

            if (consensusFactory == null)
            {
                throw new ArgumentNullException(nameof(consensusFactory));
            }

            Block block = consensusFactory.CreateBlock();

            block.ReadWrite(bytes, consensusFactory);

            return(block);
        }
Exemplo n.º 2
0
        public static Block Parse(string hex, ConsensusFactory consensusFactory)
        {
            if (string.IsNullOrEmpty(hex))
            {
                throw new ArgumentNullException(nameof(hex));
            }

            if (consensusFactory == null)
            {
                throw new ArgumentNullException(nameof(consensusFactory));
            }

            Block block = consensusFactory.CreateBlock();

            block.ReadWrite(Encoders.Hex.DecodeData(hex), consensusFactory);

            return(block);
        }
Exemplo n.º 3
0
        public static NBitcoin.Block CreateGenesis(ConsensusFactory consensusFactory, uint genesisTime, uint nonce, uint bits, int version, Money reward)
        {
            string timeStamp           = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";
            var    genesisOutputScript = new Script(Op.GetPushOp(Encoders.Hex.DecodeData("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f")), OpcodeType.OP_CHECKSIG);

            NBitcoin.Transaction genesisTransaction = consensusFactory.CreateTransaction();

            // TODO: Similar potential problem to Cirrus genesis definition
            if (genesisTransaction is IPosTransactionWithTime posTx)
            {
                posTx.Time = genesisTime;
            }

            genesisTransaction.Version = 1;
            genesisTransaction.AddInput(new TxIn()
            {
                ScriptSig = new Script(Op.GetPushOp(486604799), new Op()
                {
                    Code     = (OpcodeType)0x1,
                    PushData = new[] { (byte)4 }
                }, Op.GetPushOp(Encoders.ASCII.DecodeData(timeStamp)))
            });

            genesisTransaction.AddOutput(new TxOut()
            {
                Value        = reward,
                ScriptPubKey = genesisOutputScript
            });

            NBitcoin.Block genesis = consensusFactory.CreateBlock();
            genesis.Header.BlockTime = Utils.UnixTimeToDateTime(genesisTime);
            genesis.Header.Bits      = bits;
            genesis.Header.Nonce     = nonce;
            genesis.Header.Version   = version;
            genesis.Transactions.Add(genesisTransaction);
            genesis.Header.HashPrevBlock = uint256.Zero;
            genesis.UpdateMerkleRoot();

            ((SmartContractBlockHeader)genesis.Header).HashStateRoot = new uint256("21B463E3B52F6201C0AD6C991BE0485B6EF8C092E64583FFA655CC1B171FE856");

            return(genesis);
        }
        private static Block CreateBiblepayGenesisBlock(ConsensusFactory consensusFactory, string pszTimestamp, uint nTime,
                                                        uint nNonce, uint nBits, int nVersion, Money genesisReward)
        {
            Transaction txNew = new Transaction();

            txNew.Version = 1;

            txNew.AddInput(new TxIn()
            {
                ScriptSig = new Script(Op.GetPushOp(486604799), new Op()
                {
                    Code     = (OpcodeType)0x1,
                    PushData = new[] { (byte)4 }
                }, Op.GetPushOp(Encoders.ASCII.DecodeData(pszTimestamp)))
            });

            Script genesisOutputScript = new Script(Op.GetPushOp(Encoders.Hex.DecodeData("040184710fa689ad5023690c80f3a49c8f13f8d45b8c857fbcbc8bc4a8e4d3eb4b10f4d4604fa08dce601aaf0f470216fe1b51850b4acf21b179c45070ac7b03a9")), OpcodeType.OP_CHECKSIG);

            txNew.AddOutput(new TxOut()
            {
                Value        = genesisReward,
                ScriptPubKey = genesisOutputScript
            });

            byte[] b = new byte[1];
            b[0] = 0;
            txNew.Outputs[0].sTxOutMessage = b;
            Block genesis = consensusFactory.CreateBlock();

            genesis.Header.BlockTime = Utils.UnixTimeToDateTime(nTime);
            genesis.Header.Bits      = nBits;
            genesis.Header.Nonce     = nNonce;
            genesis.Header.Version   = 1;
            genesis.Transactions.Add(txNew);
            genesis.Header.HashPrevBlock = uint256.Zero;
            genesis.UpdateMerkleRoot();

            BiblePayTestBed();

            return(genesis);
        }
Exemplo n.º 5
0
        public Block GetBlock(uint256 blockId)
        {
            var ms        = new MemoryStream();
            var container = Configuration.GetBlocksContainer();

            try
            {
                container.GetPageBlobReference(blockId.ToString()).DownloadToStreamAsync(ms).GetAwaiter().GetResult();
                ms.Position = 0;
                Block b = ConsensusFactory.CreateBlock();
                b.ReadWrite(ms, false, Configuration.Network);
                return(b);
            }
            catch (StorageException ex)
            {
                if (ex.RequestInformation != null && ex.RequestInformation.HttpStatusCode == 404)
                {
                    return(null);
                }
                throw;
            }
        }
        protected static Block CreateBitcoinGenesisBlock(ConsensusFactory consensusFactory, uint nTime, uint nNonce, uint nBits, int nVersion, Money genesisReward)
        {
            string pszTimestamp        = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";
            var    genesisOutputScript = new Script(Op.GetPushOp(Encoders.Hex.DecodeData("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f")), OpcodeType.OP_CHECKSIG);

            Transaction txNew = consensusFactory.CreateTransaction();

            txNew.Version = 1;
            txNew.AddInput(new TxIn()
            {
                ScriptSig = new Script(Op.GetPushOp(486604799), new Op()
                {
                    Code     = (OpcodeType)0x1,
                    PushData = new[] { (byte)4 }
                }, Op.GetPushOp(Encoders.ASCII.DecodeData(pszTimestamp)))
            });
            txNew.AddOutput(new TxOut()
            {
                Value        = genesisReward,
                ScriptPubKey = genesisOutputScript
            });

            // txNew.Outputs[0].ScriptPubKey =  const CScript genesisOutputScript = CScript() << ParseHex("040184710fa689ad5023690c80f3a49c8f13f8d45b8c857fbcbc8bc4a8e4d3eb4b10f4d4604fa08dce601aaf0f470216fe1b51850b4acf21b179c45070ac7b03a9") << OP_CHECKSIG;
            byte[] b = new byte[1];
            b[0] = 0;
            txNew.Outputs[0].sTxOutMessage = b;


            Block genesis = consensusFactory.CreateBlock();

            genesis.Header.BlockTime = Utils.UnixTimeToDateTime(nTime);
            genesis.Header.Bits      = nBits;
            genesis.Header.Nonce     = nNonce;
            genesis.Header.Version   = nVersion;
            genesis.Transactions.Add(txNew);
            genesis.Header.HashPrevBlock = uint256.Zero;
            genesis.UpdateMerkleRoot();
            return(genesis);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Create a block with the specified option only. (useful for stripping data from a block).
        /// </summary>
        /// <param name="consensusFactory">The network consensus factory.</param>
        /// <param name="options">Options to keep.</param>
        /// <returns>A new block with only the options wanted.</returns>
        public Block WithOptions(ConsensusFactory consensusFactory, TransactionOptions options)
        {
            if (this.Transactions.Count == 0)
            {
                return(this);
            }

            if ((options == TransactionOptions.Witness) && this.Transactions[0].HasWitness)
            {
                return(this);
            }

            if ((options == TransactionOptions.None) && !this.Transactions[0].HasWitness)
            {
                return(this);
            }

            Block instance = consensusFactory.CreateBlock();

            using (var ms = new MemoryStream())
            {
                var bms = new BitcoinStream(ms, true, consensusFactory)
                {
                    TransactionOptions = options,
                };

                this.ReadWrite(bms);
                ms.Position = 0;
                bms         = new BitcoinStream(ms, false, consensusFactory)
                {
                    TransactionOptions = options,
                };

                instance.ReadWrite(bms);
            }

            return(instance);
        }
Exemplo n.º 8
0
        private static Block CreateXRCGenesisBlock(ConsensusFactory consensusFactory, string message, uint nTime, uint nNonce, uint nBits, int nVersion, string pubKey)
        {
            //nTime = 1512043200 => Thursday, November 30, 2017 12:00:00 PM (born XRC)
            //nTime = 1527811200 => Friday, Jun 1, 2017 12:00:00 PM (born TestXRC)
            //nBits = 0x1d00ffff (it is exactly 0x1b = 27 bytes long) => 0x00ffff0000000000000000000000000000000000000000000000000000 => 1
            //nNonce = XTimes to trying to find a genesis block
            Transaction txNew = consensusFactory.CreateTransaction();

            txNew.Version = 2;
            if (txNew is IPosTransactionWithTime posTx)
            {
                posTx.Time = nTime;
            }
            txNew.AddInput(new TxIn()
            {
                ScriptSig = new Script(Op.GetPushOp(nBits), new Op()
                {
                    Code     = (OpcodeType)0x1,
                    PushData = new[] { (byte)4 }
                }, Op.GetPushOp(Encoders.ASCII.DecodeData(message)))
            });
            txNew.AddOutput(new TxOut()
            {
                Value        = Money.Zero,
                ScriptPubKey = Script.FromBytesUnsafe(Encoders.Hex.DecodeData(pubKey))
            });

            Block genesis = consensusFactory.CreateBlock();

            genesis.Header.BlockTime = Utils.UnixTimeToDateTime(nTime);
            genesis.Header.Bits      = nBits;
            genesis.Header.Nonce     = nNonce;
            genesis.Header.Version   = nVersion;
            genesis.Transactions.Add(txNew);
            genesis.Header.HashPrevBlock = uint256.Zero;
            genesis.UpdateMerkleRoot();
            return(genesis);
        }
Exemplo n.º 9
0
        protected static Block CreateGenesisBlock(ConsensusFactory consensusFactory, uint nTime, uint nNonce, uint nBits, int nVersion, Money genesisReward, string genesisText)
        {
            Transaction txNew = consensusFactory.CreateTransaction();

            txNew.Version = 1;

            if (txNew is IPosTransactionWithTime posTx)
            {
                posTx.Time = nTime;
            }

            txNew.AddInput(new TxIn()
            {
                ScriptSig = new Script(Op.GetPushOp(0), new Op()
                {
                    Code     = (OpcodeType)0x1,
                    PushData = new[] { (byte)42 }
                }, Op.GetPushOp(Encoders.ASCII.DecodeData(genesisText)))
            });

            txNew.AddOutput(new TxOut()
            {
                Value = genesisReward,
            });

            Block genesis = consensusFactory.CreateBlock();

            genesis.Header.BlockTime = Utils.UnixTimeToDateTime(nTime);
            genesis.Header.Bits      = nBits;
            genesis.Header.Nonce     = nNonce;
            genesis.Header.Version   = nVersion;
            genesis.Transactions.Add(txNew);
            genesis.Header.HashPrevBlock = uint256.Zero;
            genesis.UpdateMerkleRoot();

            return(genesis);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Mines a new genesis block, to use with a new network.
        /// Typically, 3 such genesis blocks need to be created when bootstrapping a new coin: for Main, Test and Reg networks.
        /// </summary>
        /// <param name="consensusFactory">
        /// The consensus factory used to create transactions and blocks.
        /// Use <see cref="PosConsensusFactory"/> for proof-of-stake based networks.
        /// </param>
        /// <param name="coinbaseText">
        /// Traditionally a news headline from the day of the launch, but could be any string or link.
        /// This will be inserted in the input coinbase transaction script.
        /// It should be shorter than 92 characters.
        /// </param>
        /// <param name="target">
        /// The difficulty target under which the hash of the block need to be.
        /// Some more details: As an example, the target for the Stratis Main network is 00000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff.
        /// To make it harder to mine the genesis block, have more zeros at the beginning (keeping the length the same). This will make the target smaller, so finding a number under it will be more difficult.
        /// To make it easier to mine the genesis block ,do the opposite. Example of an easy one: 00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff.
        /// Make the Test and Reg targets ones easier to find than the Main one so that you don't wait too long to mine the genesis block.
        /// </param>
        /// <param name="genesisReward">
        /// Specify how many coins to put in the genesis transaction's output. These coins are unspendable.
        /// </param>
        /// <param name="version">
        /// The version of the transaction and the block header set in the genesis block.
        /// </param>
        /// <example>
        /// The following example shows the creation of a genesis block.
        /// <code>
        /// Block genesis = MineGenesisBlock(new PosConsensusFactory(), "Some topical headline.", new Target(new uint256("000fffff00000000000000000000000000000000000000000000000000000000")), Money.Coins(50m));
        /// BlockHeader header = genesis.Header;
        /// Console.WriteLine("Make a note of the following values:");
        /// Console.WriteLine("bits: " + header.Bits);
        /// Console.WriteLine("nonce: " + header.Nonce);
        /// Console.WriteLine("time: " + header.Time);
        /// Console.WriteLine("version: " + header.Version);
        /// Console.WriteLine("hash: " + header.GetHash());
        /// Console.WriteLine("merkleroot: " + header.HashMerkleRoot);
        /// </code>
        /// </example>
        /// <returns>A genesis block.</returns>
        public static Block MineGenesisBlock(ConsensusFactory consensusFactory, string coinbaseText, Target target, Money genesisReward, int version = 1)
        {
            if (consensusFactory == null)
            {
                throw new ArgumentException($"Parameter '{nameof(consensusFactory)}' cannot be null. Use 'new ConsensusFactory()' for Bitcoin-like proof-of-work blockchains and 'new PosConsensusFactory()' for Stratis-like proof-of-stake blockchains.");
            }

            if (string.IsNullOrEmpty(coinbaseText))
            {
                throw new ArgumentException($"Parameter '{nameof(coinbaseText)}' cannot be null. Use a news headline or any other appropriate string.");
            }

            if (target == null)
            {
                throw new ArgumentException($"Parameter '{nameof(target)}' cannot be null. Example use: new Target(new uint256(\"0000ffff00000000000000000000000000000000000000000000000000000000\"))");
            }

            if (coinbaseText.Length >= 92)
            {
                throw new ArgumentException($"Parameter '{nameof(coinbaseText)}' should be shorter than 92 characters.");
            }

            if (genesisReward == null)
            {
                throw new ArgumentException($"Parameter '{nameof(genesisReward)}' cannot be null. Example use: 'Money.Coins(50m)'.");
            }

            DateTimeOffset time     = DateTimeOffset.Now;
            uint           unixTime = Utils.DateTimeToUnixTime(time);

            Transaction txNew = consensusFactory.CreateTransaction();

            txNew.Version = (uint)version;
            if (txNew is IPosTransactionWithTime posTx)
            {
                posTx.Time = unixTime;
            }
            txNew.AddInput(new TxIn()
            {
                ScriptSig = new Script(
                    Op.GetPushOp(0),
                    new Op()
                {
                    Code     = (OpcodeType)0x1,
                    PushData = new[] { (byte)42 }
                },
                    Op.GetPushOp(Encoders.ASCII.DecodeData(coinbaseText)))
            });

            txNew.AddOutput(new TxOut()
            {
                Value = genesisReward,
            });

            Block genesis = consensusFactory.CreateBlock();

            genesis.Header.BlockTime = time;
            genesis.Header.Bits      = target;
            genesis.Header.Nonce     = 0;
            genesis.Header.Version   = version;
            genesis.Transactions.Add(txNew);
            genesis.Header.HashPrevBlock = uint256.Zero;
            genesis.UpdateMerkleRoot();

            // Iterate over the nonce until the proof-of-work is valid.
            // This will mean the block header hash is under the target.
            while (!genesis.CheckProofOfWork())
            {
                genesis.Header.Nonce++;
                if (genesis.Header.Nonce == 0)
                {
                    genesis.Header.Time++;
                }
            }

            return(genesis);
        }