예제 #1
0
        static void Main(string[] args)
        {
            // Example 3-3. Running getinfo via Bitcoin Core’s JSON-RPC API - Seite 49
            // Benutze den RPC Wrapper von NBitcoin:
            NetworkCredential myCredential = new NetworkCredential("bitcoinrpc", "d0n7Blue");
            Uri       myUri       = new Uri("http://localhost.:8332/");
            RPCClient myClient    = new RPCClient(myCredential, myUri);
            int       blockheight = myClient.GetBlockCount();

            Console.WriteLine($"Anzahl Blöcke/Blockheight: {blockheight}");

            // Example 3-4. Retrieving a transaction and iterating its outputs
            // Alice's transaction ID
            NBitcoin.uint256 txid = uint256.Parse("0627052b6f28912f2703066a912ea577f2ce4da4caa5a5fbd8a57286c345c2f2");

            // First, retrieve the raw transaction in hex
            string raw_tx = myClient.GetRawTransaction(txid).ToString();

            Console.WriteLine(raw_tx);


            // Decode the transaction hex into a JSON object
            //Transaction decodedTx = myClient.DecodeRawTransactionAsync(raw_tx);
            //Transaction decodedTx = myClient.DecodeRawTransaction(raw_tx);
            //Console.WriteLine(raw_tx);

            //var outputList = raw_tx.Outputs;
            //foreach (var output in outputList)
            //{
            //    Console.WriteLine(output);
            //}



            // Example 3-5. Retrieving a block and adding all the transaction outputs - Seite 50
            int blockheightOfAliceTransaction = 277316;

            // Get the block hash of block with height 277316
            var blockhash = myClient.GetBlockHash(blockheightOfAliceTransaction);

            // Retrieve the block by its hash
            var block = myClient.GetBlock(blockhash);
            var listOfTransactions = block.Transactions;

            Console.WriteLine($"blockheight of Alice's Transaction: {blockheightOfAliceTransaction}\n Blockhash: {blockhash}\n");
            NBitcoin.Money sumOfTrans = 0;
            foreach (var trans in listOfTransactions)
            {
                sumOfTrans += trans.TotalOut;
            }
            // Die Summe stimmt! Siehe Seite 51:
            Console.WriteLine($"Bitcoin Wert insgesamt des Blocks: {sumOfTrans.ToString()}");
        }
예제 #2
0
        public static List <NB.Coin> SpentAllCoins(List <NB.Coin> unspentCoins, decimal fees, ref NB.Money fee,
                                                   ref NB.Money amountToSend)
        {
            var size         = 78;
            var CoinsToSpend = new List <NB.Coin>();

            amountToSend = NB.Money.Zero;
            foreach (var coin in unspentCoins.OrderByDescending(x => x.Amount))
            {
                size += 180;
                CoinsToSpend.Add(coin);
                amountToSend += coin.Amount;
            }

            fee           = new NB.Money(size * (long)(fees / 1000));
            amountToSend -= fee;
            return(CoinsToSpend);
        }
예제 #3
0
        public static List <NB.Coin> GetUnspentCoins(Data walletData, bool JustConfirmed = true)
        {
            var UnspentCoins = new List <NB.Coin>();

            foreach (var outp in walletData.unspent_Outputs)
            {
                var address = NB.BitcoinAddress.Create(outp.address);
                var hash    = new NB.uint256(outp.hash);
                var amount  = new NB.Money(outp.value, NB.MoneyUnit.BTC);
                if (outp.confirmations < 3 && JustConfirmed)
                {
                    continue;
                }
                UnspentCoins.Add(new NB.Coin(hash, (uint)outp.index, amount, address.ScriptPubKey));
            }

            return(UnspentCoins);
        }
예제 #4
0
        public static List <NB.Coin> GetCoinsToSpend(List <NB.Coin> unspentCoins, decimal fees, NB.Money amountToSend,
                                                     ref NB.Money fee, out bool haveEnough)
        {
            var size         = 78;
            var CoinsToSpend = new List <NB.Coin>();

            haveEnough = false;
            foreach (var coin in unspentCoins.OrderByDescending(x => x.Amount))
            {
                size += 180;
                fee   = new NB.Money(size * (long)(fees / 1000));
                CoinsToSpend.Add(coin);
                if (CoinsToSpend.Sum(x => x.Amount) < amountToSend + fee)
                {
                }
                else
                {
                    haveEnough = true;
                    break;
                }
            }

            return(CoinsToSpend);
        }
예제 #5
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;
            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;
        }
예제 #6
0
        public static List <UTXO> GetSpecifiedUTXO(string sAddress, NBitcoin.Money nTotalAmount)
        {
            List <UTXO> lUTXO = new List <UTXO>();

            try
            {
                string         sURL        = GetChosenSanctuary() + "/rest/getaddressutxos/" + sAddress;
                MyWebClient    w           = new MyWebClient();
                string         sData       = w.DownloadString(sURL);
                dynamic        oJson       = JsonConvert.DeserializeObject <dynamic>(sData);
                UTXO           u           = new UTXO();
                NBitcoin.Money nTotalAdded = 0;
                foreach (var j in oJson)
                {
                    u.index   = (int)j["outputIndex"].Value;
                    u.Amount  = new NBitcoin.Money((decimal)j["value"], NBitcoin.MoneyUnit.BTC);
                    u.TXID    = new NBitcoin.uint256((string)j["txid"]);
                    u.Height  = (int)j["height"].Value;
                    u.Address = j["address"].Value;

                    // Pointers to spent coins
                    for (int i = 0; i < ListSpentUTXO.Count; i++)
                    {
                        UTXO SpentUTXO = ListSpentUTXO[i];
                        if (SpentUTXO.TXID.ToString() == u.TXID.ToString())
                        {
                            bool bAlreadyUsed = false;
                            for (int k = 0; k < lUTXO.Count; k++)
                            {
                                if (lUTXO[k].TXID == SpentUTXO.SpentToTXID)
                                {
                                    bAlreadyUsed = true;
                                }
                            }
                            if (!bAlreadyUsed)
                            {
                                u.TXID   = new NBitcoin.uint256(SpentUTXO.SpentToTXID);
                                u.Amount = SpentUTXO.SpentToNewChangeAmount;
                                u.index  = SpentUTXO.SpentToIndex;
                            }
                        }
                    }

                    // End of spent coins
                    if (u.Amount > 0)
                    {
                        lUTXO.Add(u);
                        nTotalAdded += u.Amount;
                        if (nTotalAdded > nTotalAmount)
                        {
                            return(lUTXO);
                        }
                    }
                }
                return(lUTXO);
            }
            catch (Exception ex)
            {
                Log("Error in GetSpecifiedUTXO::" + ex.Message);
                return(lUTXO);
            }
        }
예제 #7
0
        private Block CreateGenesisBlock(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";
            Script genesisOutputScript = new Script(Op.GetPushOp(Encoders.Hex.DecodeData("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f")), OpcodeType.OP_CHECKSIG);

            return(CreateGenesisBlock(pszTimestamp, genesisOutputScript, nTime, nNonce, nBits, nVersion, genesisReward));
        }
예제 #8
0
        private Block CreateGenesisBlock(string pszTimestamp, Script genesisOutputScript, 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)))
            });
            txNew.AddOutput(new TxOut()
            {
                Value        = genesisReward,
                ScriptPubKey = genesisOutputScript
            });
            Block genesis = new Block();

            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);
        }
예제 #9
0
        private void InitMain()
        {
            SpendableCoinbaseDepth = 100;
            name = "Main";

            consensus.SubsidyHalvingInterval      = 210000;
            consensus.MajorityEnforceBlockUpgrade = 750;
            consensus.MajorityRejectBlockOutdated = 950;
            consensus.MajorityWindow              = 1000;
            consensus.BIP34Height                 = 227931;
            consensus.BIP34Hash                   = new uint256("0x000000000000024b89b42a942fe0d9fea3bb44ab7bd1b19115dd6a759c0808b8");
            consensus.PowLimit                    = new Target(new uint256("00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff"));
            consensus.SegWitHeight                = 2000000000;
            consensus.PowTargetTimespan           = TimeSpan.FromSeconds(14 * 24 * 60 * 60);   // two weeks
            consensus.PowTargetSpacing            = TimeSpan.FromSeconds(10 * 60);
            consensus.PowAllowMinDifficultyBlocks = false;
            consensus.PowNoRetargeting            = false;

            // The message start string is designed to be unlikely to occur in normal data.
            // The characters are rarely used upper ASCII, not valid as UTF-8, and produce
            // a large 4-byte int at any alignment.
            magic                   = 0xD9B4BEF9;
            vAlertPubKey            = Encoders.Hex.DecodeData("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284");
            nDefaultPort            = 8333;
            nRPCPort                = 8332;
            nSubsidyHalvingInterval = 210000;

            genesis = CreateGenesisBlock(1231006505, 2083236893, 0x1d00ffff, 1, Money.Coins(50m));
            consensus.HashGenesisBlock = genesis.GetHash();
            assert(consensus.HashGenesisBlock == uint256.Parse("0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f"));
            assert(genesis.Header.HashMerkleRoot == uint256.Parse("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
#if !PORTABLE
            vSeeds.Add(new DNSSeedData("bitcoin.sipa.be", "seed.bitcoin.sipa.be"));                   // Pieter Wuille
            vSeeds.Add(new DNSSeedData("bluematt.me", "dnsseed.bluematt.me"));                        // Matt Corallo
            vSeeds.Add(new DNSSeedData("dashjr.org", "dnsseed.bitcoin.dashjr.org"));                  // Luke Dashjr
            vSeeds.Add(new DNSSeedData("bitcoinstats.com", "seed.bitcoinstats.com"));                 // Christian Decker
            vSeeds.Add(new DNSSeedData("xf2.org", "bitseed.xf2.org"));                                // Jeff Garzik
            vSeeds.Add(new DNSSeedData("bitcoin.jonasschnelli.ch", "seed.bitcoin.jonasschnelli.ch")); // Jonas Schnelli
#endif
            base58Prefixes[(int)Base58Type.PUBKEY_ADDRESS]             = new byte[] { (0) };
            base58Prefixes[(int)Base58Type.SCRIPT_ADDRESS]             = new byte[] { (5) };
            base58Prefixes[(int)Base58Type.SECRET_KEY]                 = new byte[] { (128) };
            base58Prefixes[(int)Base58Type.ENCRYPTED_SECRET_KEY_NO_EC] = new byte[] { 0x01, 0x42 };
            base58Prefixes[(int)Base58Type.ENCRYPTED_SECRET_KEY_EC]    = new byte[] { 0x01, 0x43 };
            base58Prefixes[(int)Base58Type.EXT_PUBLIC_KEY]             = new byte[] { (0x04), (0x88), (0xB2), (0x1E) };
            base58Prefixes[(int)Base58Type.EXT_SECRET_KEY]             = new byte[] { (0x04), (0x88), (0xAD), (0xE4) };
            base58Prefixes[(int)Base58Type.PASSPHRASE_CODE]            = new byte[] { 0x2C, 0xE9, 0xB3, 0xE1, 0xFF, 0x39, 0xE2 };
            base58Prefixes[(int)Base58Type.CONFIRMATION_CODE]          = new byte[] { 0x64, 0x3B, 0xF6, 0xA8, 0x9A };
            base58Prefixes[(int)Base58Type.STEALTH_ADDRESS]            = new byte[] { 0x2a };
            base58Prefixes[(int)Base58Type.ASSET_ID]        = new byte[] { 23 };
            base58Prefixes[(int)Base58Type.COLORED_ADDRESS] = new byte[] { 0x13 };
            base58Prefixes[(int)Base58Type.WITNESS_P2WPKH]  = new byte[] { 0x6 };
            base58Prefixes[(int)Base58Type.WITNESS_P2WSH]   = new byte[] { (10) };

#if !PORTABLE
            // Convert the pnSeeds array into usable address objects.
            Random   rand     = new Random();
            TimeSpan nOneWeek = TimeSpan.FromDays(7);
            for (int i = 0; i < pnSeed.Length; i++)
            {
                // It'll only connect to one or two seed nodes because once it connects,
                // it'll get a pile of addresses with newer timestamps.
                NetworkAddress addr = new NetworkAddress();
                // Seed nodes are given a random 'last seen time' of between one and two
                // weeks ago.
                addr.Time     = DateTime.UtcNow - (TimeSpan.FromSeconds(rand.NextDouble() * nOneWeek.TotalSeconds)) - nOneWeek;
                addr.Endpoint = Utils.ParseIpEndpoint(pnSeed[i], DefaultPort);
                vFixedSeeds.Add(addr);
            }
#endif
        }
예제 #10
0
 public Block CreateNextBlockWithCoinbase(PubKey pubkey, Money value, DateTimeOffset now)
 {
     return(CreateNextBlockWithCoinbase(pubkey, value, now, Consensus.Main.ConsensusFactory));
 }
예제 #11
0
 public Block CreateNextBlockWithCoinbase(PubKey pubkey, Money value, ConsensusFactory consensusFactory)
 {
     return(CreateNextBlockWithCoinbase(pubkey, value, DateTimeOffset.UtcNow, consensusFactory));
 }
예제 #12
0
파일: Coin.cs 프로젝트: long20p/CoinBag
 public ScriptCoin(uint256 txHash, uint outputIndex, Money amount, Script scriptPubKey, Script redeem)
     : base(txHash, outputIndex, amount, scriptPubKey)
 {
     Redeem = redeem;
     AssertCoherent();
 }
예제 #13
0
파일: Coin.cs 프로젝트: long20p/CoinBag
 public Coin(uint256 fromTxHash, uint fromOutputIndex, Money amount, Script scriptPubKey)
 {
     Outpoint = new OutPoint(fromTxHash, fromOutputIndex);
     TxOut    = new TxOut(amount, scriptPubKey);
 }