Esempio n. 1
0
 public Block GetBlock(uint256 id, List<byte[]> searchedData)
 {
     var block = Get(id);
     if(block == null)
         return null;
     return block;
 }
		public Transaction GetFromCache(uint256 txId)
		{
			using(@lock.LockRead())
			{
				return _Transactions.TryGet(txId);
			}
		}
Esempio n. 3
0
 public void ComputeChecksum(uint256 hashBlock)
 {
     MemoryStream ms = new MemoryStream();
     hashBlock.ReadWrite(ms, true);
     this.ReadWrite(ms, true);
     CalculatedChecksum = Hashes.Hash256(ms.ToArray());
 }
Esempio n. 4
0
        public void Setup()
        {
            var value = new Span <byte>(new byte[32]);

            new Random().NextBytes(value);

            _nBitcoinData      = new uint256(value.ToArray());
            _mithrilShardsData = new Core.DataTypes.UInt256(value);
        }
Esempio n. 5
0
 public BlockHeader GetHeader(uint256 hash)
 {
     var pos = _Index.Get<DiskBlockPos>(hash.ToString());
     if(pos == null)
         return null;
     var stored = _Store.Enumerate(false, new DiskBlockPosRange(pos)).FirstOrDefault();
     if(stored == null)
         return null;
     return stored.Item.Header;
 }
Esempio n. 6
0
		public static void Put(this ITransactionRepository repo, uint256 txId, Transaction tx)
		{
			try
			{
				repo.PutAsync(txId, tx).Wait();
			}
			catch(AggregateException aex)
			{
				ExceptionDispatchInfo.Capture(aex.InnerException).Throw();
			}
		}
		public Task PutAsync(uint256 txId, Transaction tx)
		{
			using(@lock.LockWrite())
			{
				if(!_Transactions.ContainsKey(txId))
					_Transactions.AddOrReplace(txId, tx);
				else
					_Transactions[txId] = tx;
			}
			return _Inner.PutAsync(txId, tx);
		}
Esempio n. 8
0
		public uint256(uint256 b)
		{
			pn0 = b.pn0;
			pn1 = b.pn1;
			pn2 = b.pn2;
			pn3 = b.pn3;
			pn4 = b.pn4;
			pn5 = b.pn5;
			pn6 = b.pn6;
			pn7 = b.pn7;
		}
Esempio n. 9
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()}");
        }
Esempio n. 10
0
		public static Transaction Get(this ITransactionRepository repo, uint256 txId)
		{
			try
			{
				return repo.GetAsync(txId).Result;
			}
			catch(AggregateException aex)
			{
				ExceptionDispatchInfo.Capture(aex.InnerException).Throw();
				return null;
			}
		}
		public async Task<Transaction> GetAsync(uint256 txId)
		{
			using(HttpClient client = new HttpClient())
			{
				var tx = await client.GetAsync(BaseUri.AbsoluteUri + "transactions/" + txId + "?format=raw").ConfigureAwait(false);
				if(tx.StatusCode == System.Net.HttpStatusCode.NotFound)
					return null;
				tx.EnsureSuccessStatusCode();
				var bytes = await tx.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
				return new Transaction(bytes);
			}
		}
Esempio n. 12
0
        // Construct a partial merkle tree from a list of transaction id's, and a mask that selects a subset of them
        public PartialMerkleTree(uint256[] vTxid, bool[] vMatch)
        {
            fBad = false;
            nTransactions = (uint)vTxid.Length;

            // calculate height of tree
            int nHeight = 0;
            while(CalcTreeWidth(nHeight) > 1)
                nHeight++;

            // traverse the partial tree
            TraverseAndBuild(nHeight, 0, vTxid, vMatch);
        }
Esempio n. 13
0
 public static uint256 CheckMerkleBranch(uint256 hash, List<uint256> vMerkleBranch, int nIndex)
 {
     if(nIndex == -1)
         return 0;
     foreach(var otherside in vMerkleBranch)
     {
         if((nIndex & 1) != 0)
             hash = Hash(otherside, hash);
         else
             hash = Hash(hash, otherside);
         nIndex >>= 1;
     }
     return hash;
 }
Esempio n. 14
0
		public MerkleBlock(Block block, uint256[] txIds)
		{
			header = block.Header;

			List<bool> vMatch = new List<bool>();
			List<uint256> vHashes = new List<uint256>();
			for(int i = 0 ; i < block.Transactions.Count ; i++)
			{
				var hash = block.Transactions[i].GetHash();
				vHashes.Add(hash);
				vMatch.Add(txIds.Contains(hash));
			}
			_PartialMerkleTree = new PartialMerkleTree(vHashes.ToArray(), vMatch.ToArray());
		}
Esempio n. 15
0
		public static bool TryParse(string hex, out uint256 result)
		{
			if(hex == null)
				throw new ArgumentNullException("hex");
			result = null;
			if(hex.Length != WIDTH_BYTE * 2)
				return false;
			if(!((HexEncoder)Encoders.Hex).IsValid(hex))
				return false;
			var ret = new uint256();
			ret.SetHex(hex);
			result = ret;
			return true;
		}
Esempio n. 16
0
			public void ReadWrite(BitcoinStream stream)
			{
				if(stream.Serializing)
				{
					var b = Value.ToBytes();
					stream.ReadWrite(ref b);
				}
				else
				{
					byte[] b = new byte[WIDTH_BYTE];
					stream.ReadWrite(ref b);
					_Value = new uint256(b);
				}
			}
Esempio n. 17
0
		public static bool TryParse(string hex, out uint256 result)
		{
			if(hex == null)
				throw new ArgumentNullException("hex");
			if (hex.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
				hex = hex.Substring(2);
			result = null;
			if(hex.Length != WIDTH_BYTE * 2)
				return false;
			if(!((HexEncoder)Encoders.Hex).IsValid(hex))
				return false;			
			result = new uint256(hex);
			return true;
		}
Esempio n. 18
0
		public PartialMerkleTree(uint256[] vTxid, bool[] vMatch)
		{
			if(vMatch.Length != vTxid.Length)
				throw new ArgumentException("The size of the array of txid and matches is different");
			TransactionCount = (uint)vTxid.Length;

			MerkleNode root = MerkleNode.GetRoot(vTxid);
			BitWriter flags = new BitWriter();

			MarkNodes(root, vMatch);
			BuildCore(root, flags);

			Flags = flags.ToBitArray();
		}
Esempio n. 19
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);
        }
		public async Task<Transaction> GetAsync(uint256 txId)
		{
			bool found = false;
			Transaction result = null;
			using(@lock.LockRead())
			{
				found = _Transactions.TryGetValue(txId, out result);
			}
			if(!found)
			{
				result = await _Inner.GetAsync(txId).ConfigureAwait(false);
				using(@lock.LockWrite())
				{
					_Transactions.AddOrReplace(txId, result);
				}
			}
			return result;

		}
		public Task PutAsync(uint256 txId, Transaction tx)
		{
			if(WriteThrough)
			{
				using(@lock.LockWrite())
				{

					if(!_Transactions.ContainsKey(txId))
					{

						_Transactions.AddOrReplace(txId, tx);
						EvictIfNecessary(txId);
					}
					else
						_Transactions[txId] = tx;
				}
			}
			return _Inner.PutAsync(txId, tx);
		}
Esempio n. 22
0
        // (memory only) Sequencial id assigned to distinguish order in which blocks are received.
        //uint nSequenceId;
        public ChainedBlock(BlockHeader header,uint256 headerHash, ChainedBlock previous)
        {
            if(previous != null)
            {
                nHeight = previous.Height + 1;
            }
            this.pprev = previous;
            //this.nDataPos = pos;
            this.header = header;
            this.phashBlock = headerHash ?? header.GetHash();

            if(previous == null)
            {
                if(header.HashPrevBlock != 0)
                    throw new ArgumentException("Only the genesis block can have no previous block");
            }
            else
            {
                if(previous.HashBlock != header.HashPrevBlock)
                    throw new ArgumentException("The previous block has not the expected hash");
            }
        }
        public Block GetBlock(uint256 blockId)
        {
            var ms = new MemoryStream();
            var container = Configuration.GetBlocksContainer();
            try
            {

                container.GetPageBlobReference(blockId.ToString()).DownloadToStream(ms);
                ms.Position = 0;
                Block b = new Block();
                b.ReadWrite(ms, false);
                return b;
            }
            catch(StorageException ex)
            {
                if(ex.RequestInformation != null && ex.RequestInformation.HttpStatusCode == 404)
                {
                    return null;
                }
                throw;
            }
        }
		public async Task<Transaction> GetAsync(uint256 txId)
		{
			while(true)
			{
				using(HttpClient client = new HttpClient())
				{
					var response = await client.GetAsync(BlockrAddress + "tx/raw/" + txId).ConfigureAwait(false);
					if(response.StatusCode == HttpStatusCode.NotFound)
						return null;
					var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
					var json = JObject.Parse(result);
					var status = json["status"];
					var code = json["code"];
					if(status != null && status.ToString() == "error")
					{
						throw new BlockrException(json);
					}
					var tx = new Transaction(json["data"]["tx"]["hex"].ToString());
					return tx;
				}
			}
		}
Esempio n. 25
0
		public ECDSASignature Sign(uint256 hash)
		{
			return _ECKey.Sign(hash);
		}
Esempio n. 26
0
        private void InitMain()
        {
            SpendableCoinbaseDepth = 100;
            name = "Main";
            // 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;
            _ProofOfLimit           = new Target(~uint256.Zero >> 32);
            nSubsidyHalvingInterval = 210000;

            Transaction txNew = new Transaction();

            txNew.Version = 1;
            txNew.Inputs.Add(new TxIn());
            txNew.Outputs.Add(new TxOut());
            txNew.Inputs[0].ScriptSig     = new Script(Encoders.Hex.DecodeData("04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73"));
            txNew.Outputs[0].Value        = 50 * Money.COIN;
            txNew.Outputs[0].ScriptPubKey = new Script() + Encoders.Hex.DecodeData("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") + OpcodeType.OP_CHECKSIG;
            genesis.Transactions.Add(txNew);
            genesis.Header.HashPrevBlock = 0;
            genesis.UpdateMerkleRoot();
            genesis.Header.Version   = 1;
            genesis.Header.BlockTime = Utils.UnixTimeToDateTime(1231006505);
            genesis.Header.Bits      = 0x1d00ffff;
            genesis.Header.Nonce     = 2083236893;

            hashGenesisBlock = genesis.GetHash();
            assert(hashGenesisBlock == uint256.Parse("0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f"));
            assert(genesis.Header.HashMerkleRoot == uint256.Parse("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
#if !PORTABLE
            vSeeds.Add(new DNSSeedData("bitcoin.sipa.be", "seed.bitcoin.sipa.be"));
            vSeeds.Add(new DNSSeedData("bluematt.me", "dnsseed.bluematt.me"));
            vSeeds.Add(new DNSSeedData("dashjr.org", "dnsseed.bitcoin.dashjr.org"));
            vSeeds.Add(new DNSSeedData("bitcoinstats.com", "seed.bitcoinstats.com"));
            vSeeds.Add(new DNSSeedData("bitnodes.io", "seed.bitnodes.io"));
            vSeeds.Add(new DNSSeedData("xf2.org", "bitseed.xf2.org"));
            vSeeds.Add(new DNSSeedData("bitcoin.jonasschnelli.ch", "seed.bitcoin.jonasschnelli.ch"));
#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 };

            // Convert the pnSeeds array into usable address objects.
            Random   rand     = new Random();
            TimeSpan nOneWeek = TimeSpan.FromDays(7);
#if !PORTABLE
            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.
                IPAddress      ip   = IPAddress.Parse(pnSeed[i]);
                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 = new IPEndPoint(ip, DefaultPort);
                vFixedSeeds.Add(addr);
            }
#endif
        }
Esempio n. 27
0
 public OutPoint(uint256 hashIn, int nIn)
 {
     hash = hashIn;
     this.n = nIn == -1 ? n = uint.MaxValue : (uint)nIn;
 }
Esempio n. 28
0
 public void PutAsync(uint256 trxId, uint256 blockId)
 {
     repository.PutAsync(trxId.ToString(), blockId.AsBitcoinSerializable());
 }
Esempio n. 29
0
        // Check kernel hash target and coinstake signature
        public static bool CheckProofOfStake(IBlockRepository blockStore, ITransactionRepository trasnactionStore, IBlockTransactionMapStore mapStore,
                                             ChainedBlock pindexPrev, Transaction tx, uint nBits, out uint256 hashProofOfStake, out uint256 targetProofOfStake)
        {
            targetProofOfStake = null; hashProofOfStake = null;

            // todo: Comments on this mehtod:
            // the store objects (IBlockRepository and  ITransactionRepository) should be a singleton instance of
            // the BlockValidator and would be initiated as part of a Dependency Injection freamwork

            if (!tx.IsCoinStake)
            {
                return(false);                // error("CheckProofOfStake() : called on non-coinstake %s", tx.GetHash().ToString());
            }
            // Kernel (input 0) must match the stake hash target per coin age (nBits)
            var txIn = tx.Inputs[0];

            // First try finding the previous transaction in database
            var txPrev = trasnactionStore.Get(txIn.PrevOut.Hash);

            if (txPrev == null)
            {
                return(false);                // tx.DoS(1, error("CheckProofOfStake() : INFO: read txPrev failed"));  // previous transaction not in main chain, may occur during initial download
            }
            // Verify signature
            if (!VerifySignature(txPrev, tx, 0, ScriptVerify.None))
            {
                return(false);                // tx.DoS(100, error("CheckProofOfStake() : VerifySignature failed on coinstake %s", tx.GetHash().ToString()));
            }
            // Read block header
            var blockHashPrev = mapStore.GetBlockHash(txIn.PrevOut.Hash);
            var block         = blockHashPrev == null ? null : blockStore.GetBlock(blockHashPrev);

            if (block == null)
            {
                return(false);                //fDebug? error("CheckProofOfStake() : read block failed") : false; // unable to read block of previous transaction
            }
            // Min age requirement
            if (IsProtocolV3((int)tx.Time))
            {
                int nDepth = 0;
                if (IsConfirmedInNPrevBlocks(blockStore, txPrev, pindexPrev, StakeMinConfirmations - 1, ref nDepth))
                {
                    return(false);                    // tx.DoS(100, error("CheckProofOfStake() : tried to stake at depth %d", nDepth + 1));
                }
            }
            else
            {
                var nTimeBlockFrom = block.Header.Time;
                if (nTimeBlockFrom + StakeMinAge > tx.Time)
                {
                    return(false);                    // error("CheckProofOfStake() : min age violation");
                }
            }

            if (!CheckStakeKernelHash(pindexPrev, nBits, block, txPrev, txIn.PrevOut, tx.Time, out hashProofOfStake, out targetProofOfStake, false))
            {
                return(false);                // tx.DoS(1, error("CheckProofOfStake() : INFO: check kernel failed on coinstake %s, hashProof=%s", tx.GetHash().ToString(), hashProofOfStake.ToString())); // may occur during initial download or if behind on block chain sync
            }
            return(true);
        }
Esempio n. 30
0
        private static bool CheckStakeKernelHash(ChainedBlock pindexPrev, uint nBits, Block blockFrom, Transaction txPrev,
                                                 OutPoint prevout, uint nTimeTx, out uint256 hashProofOfStake, out uint256 targetProofOfStake, bool fPrintProofOfStake)
        {
            targetProofOfStake = null; hashProofOfStake = null;

            if (IsProtocolV2(pindexPrev.Height + 1))
            {
                return(CheckStakeKernelHashV2(pindexPrev, nBits, blockFrom.Header.Time, txPrev, prevout, nTimeTx, out hashProofOfStake, out targetProofOfStake, fPrintProofOfStake));
            }
            else
            {
                return(CheckStakeKernelHashV1());
            }
        }
Esempio n. 31
0
 private string GetId(uint256 txId)
 {
     return("tx-" + txId.ToString());
 }
Esempio n. 32
0
 public ECDSASignature Sign(uint256 hash)
 {
     return(_ECKey.Sign(hash));
 }
Esempio n. 33
0
        private static bool Check(byte[] vch)
        {
            var candidateKey = new uint256(vch.SafeSubarray(0, KEY_SIZE));

            return(candidateKey > 0 && candidateKey < N);
        }
Esempio n. 34
0
 public TransactionSignature Sign(uint256 hash, SigHash sigHash)
 {
     return(new TransactionSignature(Sign(hash), sigHash));
 }
 public WitScriptId(uint256 value)
     : base(value.ToBytes())
 {
 }
 public TransactionNotFoundException(string message, uint256 txId)
     : this(message, txId, null)
 {
 }
 public TransactionNotFoundException(uint256 txId)
     : this(null, txId, null)
 {
 }
Esempio n. 38
0
 public void PushChange(ChainChange change, uint256 blockHash)
 {
     Process(change, blockHash);
     _Changes.WriteNext(change);
     _NextToProcess++;
 }
Esempio n. 39
0
 public ChainedBlock GetBlock(uint256 hash)
 {
     return(GetBlock(hash, false));
 }
Esempio n. 40
0
 public Task <Transaction> GetAsync(uint256 txId)
 {
     return(this.repository.GetAsync <Transaction>(GetId(txId)));
 }
Esempio n. 41
0
 public Task PutAsync(uint256 txId, Transaction tx)
 {
     return(Task.FromResult(false));
 }
Esempio n. 42
0
 public Task PutAsync(uint256 blockId, Block block)
 {
     return(_Repository.PutAsync(blockId.ToString(), block));
 }
Esempio n. 43
0
 public sealed override void Set(uint256 blockid, BlockStake blockStake)
 {
     // throw if item already exists
     this.items.Add(blockid, blockStake);
 }
Esempio n. 44
0
 public ChainedBlock(BlockHeader header, int height)
 {
     nHeight = height;
     //this.nDataPos = pos;
     this.header = header;
     this.phashBlock = header.GetHash();
 }
Esempio n. 45
0
 public override BlockStake Get(uint256 blockid)
 {
     return(this.items.TryGet(blockid));
 }
Esempio n. 46
0
		public ChainedBlock(BlockHeader header, int height)
		{
			if(header == null)
				throw new ArgumentNullException("header");
			nHeight = height;
			//this.nDataPos = pos;
			this.header = header;
			this.phashBlock = header.GetHash();
		}
Esempio n. 47
0
 public OutPoint(uint256 hashIn, uint nIn)
 {
     hash = hashIn;
     n = nIn;
 }
Esempio n. 48
0
		public TransactionSignature Sign(uint256 hash, SigHash sigHash)
		{
			return new TransactionSignature(Sign(hash), sigHash);
		}
Esempio n. 49
0
 public SmartContractPoABlockHeader() : base()
 {
     this.hashStateRoot = 0;
     this.receiptRoot   = 0;
     this.logsBloom     = new Bloom();
 }
Esempio n. 50
0
        public bool Contains(uint256 hash, bool includeBranch = false)
        {
            ChainedBlock pindex = GetBlock(hash, includeBranch);

            return(pindex != null);
        }
Esempio n. 51
0
		public ChainedBlock FindAncestorOrSelf(uint256 blockHash)
		{
			ChainedBlock currentBlock = this;
			while(currentBlock != null && currentBlock.HashBlock != blockHash)
			{
				currentBlock = currentBlock.Previous;
			}
			return currentBlock;
		}
Esempio n. 52
0
 public Task <Block> GetBlockAsync(uint256 blockId)
 {
     return(_Repository.GetAsync <Block>(blockId.ToString()));
 }
Esempio n. 53
0
		public byte[] SignCompact(uint256 hash)
		{
			var sig = _ECKey.Sign(hash);
			// Now we have to work backwards to figure out the recId needed to recover the signature.
			int recId = -1;
			for(int i = 0 ; i < 4 ; i++)
			{
				ECKey k = ECKey.RecoverFromSignature(i, sig, hash, IsCompressed);
				if(k != null && k.GetPubKey(IsCompressed).ToHex() == PubKey.ToHex())
				{
					recId = i;
					break;
				}
			}

			if(recId == -1)
				throw new InvalidOperationException("Could not construct a recoverable key. This should never happen.");

			int headerByte = recId + 27 + (IsCompressed ? 4 : 0);

			byte[] sigData = new byte[65];  // 1 header + 32 bytes for R + 32 bytes for S

			sigData[0] = (byte)headerByte;

			Array.Copy(Utils.BigIntegerToBytes(sig.R, 32), 0, sigData, 1, 32);
			Array.Copy(Utils.BigIntegerToBytes(sig.S, 32), 0, sigData, 33, 32);
			return sigData;
		}
Esempio n. 54
0
 public Target(uint256 target)
 {
     _Target = new BigInteger(target.ToBytes(false));
     _Target = new Target(this.ToCompact())._Target;
 }
Esempio n. 55
0
		private static bool Check(byte[] vch)
		{
			var candidateKey = new uint256(vch.SafeSubarray(0, KEY_SIZE));
			return candidateKey > 0 && candidateKey < N;
		}
Esempio n. 56
0
 /// <summary>
 /// If called, GetHash becomes cached, only use if you believe the instance will not be modified after calculation. Calling it a second type invalidate the cache.
 /// </summary>
 public void CacheHashes()
 {
     _Hashes = new uint256[1];
 }
Esempio n. 57
0
        // select a block from the candidate blocks in vSortedByTimestamp, excluding
        // already selected blocks in vSelectedBlocks, and with timestamp up to
        // nSelectionIntervalStop.
        private static bool SelectBlockFromCandidates(ChainedBlock chainIndex, SortedDictionary <uint, uint256> sortedByTimestamp,
                                                      Dictionary <uint256, ChainedBlock> mapSelectedBlocks,
                                                      long nSelectionIntervalStop, ulong nStakeModifierPrev, out ChainedBlock pindexSelected)
        {
            bool    fSelected = false;
            uint256 hashBest  = 0;

            pindexSelected = null;

            foreach (var item in sortedByTimestamp)
            {
                var pindex = chainIndex.FindAncestorOrSelf(item.Value);
                if (pindex == null)
                {
                    return(false);                    // error("SelectBlockFromCandidates: failed to find block index for candidate block %s", item.second.ToString());
                }
                if (fSelected && pindex.Header.Time > nSelectionIntervalStop)
                {
                    break;
                }

                if (mapSelectedBlocks.Keys.Any(key => key == pindex.HashBlock))
                {
                    continue;
                }

                // compute the selection hash by hashing its proof-hash and the
                // previous proof-of-stake modifier
                uint256 hashSelection;
                using (var ms = new MemoryStream())
                {
                    var serializer = new BitcoinStream(ms, true);
                    serializer.ReadWrite(pindex.Header.PosParameters.HashProof);
                    serializer.ReadWrite(nStakeModifierPrev);

                    hashSelection = Hashes.Hash256(ms.ToArray());
                }

                // the selection hash is divided by 2**32 so that proof-of-stake block
                // is always favored over proof-of-work block. this is to preserve
                // the energy efficiency property
                if (pindex.Header.PosParameters.IsProofOfStake())
                {
                    hashSelection >>= 32;
                }

                if (fSelected && hashSelection < hashBest)
                {
                    hashBest       = hashSelection;
                    pindexSelected = pindex;
                }
                else if (!fSelected)
                {
                    fSelected      = true;
                    hashBest       = hashSelection;
                    pindexSelected = pindex;
                }
            }

            //LogPrint("stakemodifier", "SelectBlockFromCandidates: selection hash=%s\n", hashBest.ToString());
            return(fSelected);
        }
Esempio n. 58
0
        // Stratis kernel protocol
        // coinstake must meet hash target according to the protocol:
        // kernel (input 0) must meet the formula
        //     hash(nStakeModifier + txPrev.block.nTime + txPrev.nTime + txPrev.vout.hash + txPrev.vout.n + nTime) < bnTarget * nWeight
        // this ensures that the chance of getting a coinstake is proportional to the
        // amount of coins one owns.
        // The reason this hash is chosen is the following:
        //   nStakeModifier: scrambles computation to make it very difficult to precompute
        //                   future proof-of-stake
        //   txPrev.block.nTime: prevent nodes from guessing a good timestamp to
        //                       generate transaction for future advantage,
        //                       obsolete since v3
        //   txPrev.nTime: slightly scrambles computation
        //   txPrev.vout.hash: hash of txPrev, to reduce the chance of nodes
        //                     generating coinstake at the same time
        //   txPrev.vout.n: output number of txPrev, to reduce the chance of nodes
        //                  generating coinstake at the same time
        //   nTime: current timestamp
        //   block/tx hash should not be used here as they can be generated in vast
        //   quantities so as to generate blocks faster, degrading the system back into
        //   a proof-of-work situation.
        //
        private static bool CheckStakeKernelHashV2(ChainedBlock pindexPrev, uint nBits, uint nTimeBlockFrom,
                                                   Transaction txPrev, OutPoint prevout, uint nTimeTx, out uint256 hashProofOfStake, out uint256 targetProofOfStake, bool fPrintProofOfStake)
        {
            targetProofOfStake = null; hashProofOfStake = null;

            if (nTimeTx < txPrev.Time)        // Transaction timestamp violation
            {
                return(false);                //error("CheckStakeKernelHash() : nTime violation");
            }
            // Base target
            var bnTarget = new Target(nBits).ToBigInteger();

            // Weighted target
            var nValueIn = txPrev.Outputs[prevout.N].Value.Satoshi;
            var bnWeight = BigInteger.ValueOf(nValueIn);

            bnTarget = bnTarget.Multiply(bnWeight);

            // todo: investigate this issue, is the convertion to uint256 similar to the c++ implementation
            //targetProofOfStake = Target.ToUInt256(bnTarget);

            var     nStakeModifier       = pindexPrev.Header.PosParameters.StakeModifier;
            uint256 bnStakeModifierV2    = pindexPrev.Header.PosParameters.StakeModifierV2;
            int     nStakeModifierHeight = pindexPrev.Height;
            var     nStakeModifierTime   = pindexPrev.Header.Time;

            // Calculate hash
            using (var ms = new MemoryStream())
            {
                var serializer = new BitcoinStream(ms, true);
                if (IsProtocolV3((int)nTimeTx))
                {
                    serializer.ReadWrite(bnStakeModifierV2);
                }
                else
                {
                    serializer.ReadWrite(nStakeModifier);
                    serializer.ReadWrite(nTimeBlockFrom);
                }

                serializer.ReadWrite(txPrev.Time);
                serializer.ReadWrite(prevout.Hash);
                serializer.ReadWrite(prevout.N);
                serializer.ReadWrite(nTimeTx);

                hashProofOfStake = Hashes.Hash256(ms.ToArray());
            }

            if (fPrintProofOfStake)
            {
                //LogPrintf("CheckStakeKernelHash() : using modifier 0x%016x at height=%d timestamp=%s for block from timestamp=%s\n",
                //	nStakeModifier, nStakeModifierHeight,
                //	DateTimeStrFormat(nStakeModifierTime),

                //	DateTimeStrFormat(nTimeBlockFrom));

                //LogPrintf("CheckStakeKernelHash() : check modifier=0x%016x nTimeBlockFrom=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n",
                //	nStakeModifier,
                //	nTimeBlockFrom, txPrev.nTime, prevout.n, nTimeTx,
                //	hashProofOfStake.ToString());
            }

            // Now check if proof-of-stake hash meets target protocol
            var hashProofOfStakeTarget = new BigInteger(hashProofOfStake.ToBytes(false));

            if (hashProofOfStakeTarget.CompareTo(bnTarget) > 0)
            {
                return(false);
            }


            //  if (fDebug && !fPrintProofOfStake)
            //  {
            //		LogPrintf("CheckStakeKernelHash() : using modifier 0x%016x at height=%d timestamp=%s for block from timestamp=%s\n",
            //		nStakeModifier, nStakeModifierHeight,
            //		DateTimeStrFormat(nStakeModifierTime),

            //		DateTimeStrFormat(nTimeBlockFrom));

            //		LogPrintf("CheckStakeKernelHash() : pass modifier=0x%016x nTimeBlockFrom=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n",
            //		nStakeModifier,
            //		nTimeBlockFrom, txPrev.nTime, prevout.n, nTimeTx,
            //		hashProofOfStake.ToString());
            //  }

            return(true);
        }
Esempio n. 59
0
 public static Block GetBlock(this IBlockRepository repository, uint256 blockId)
 {
     return(repository.GetBlockAsync(blockId).GetAwaiter().GetResult());
 }
Esempio n. 60
0
 public Task PutAsync(uint256 txId, Transaction tx)
 {
     return(this.repository.PutAsync(GetId(txId), tx));
 }