Example #1
0
		public void GetSigOpCount()
		{
			// Test CScript::GetSigOpCount()
			Script s1 = new Script();
			Assert.Equal(s1.GetSigOpCount(false), 0U);
			Assert.Equal(s1.GetSigOpCount(true), 0U);

			uint160 dummy = new uint160(0);
			s1 = s1 + OpcodeType.OP_1 + dummy.ToBytes() + dummy.ToBytes() + OpcodeType.OP_2 + OpcodeType.OP_CHECKMULTISIG;
			Assert.Equal(s1.GetSigOpCount(true), 2U);
			s1 = s1 + OpcodeType.OP_IF + OpcodeType.OP_CHECKSIG + OpcodeType.OP_ENDIF;
			Assert.Equal(s1.GetSigOpCount(true), 3U);
			Assert.Equal(s1.GetSigOpCount(false), 21U);

			Script p2sh = PayToScriptHashTemplate.Instance.GenerateScriptPubKey(s1);
			Script scriptSig = PayToScriptHashTemplate.Instance.GenerateScriptSig(new[] { (Op)OpcodeType.OP_0 }, s1);
			Assert.Equal(p2sh.GetSigOpCount(scriptSig), 3U);

			PubKey[] keys = Enumerable.Range(0, 3).Select(_ => new Key(true).PubKey).ToArray();

			Script s2 = PayToMultiSigTemplate.Instance.GenerateScriptPubKey(1, keys);
			Assert.Equal(s2.GetSigOpCount(true), 3U);
			Assert.Equal(s2.GetSigOpCount(false), 20U);

			p2sh = PayToScriptHashTemplate.Instance.GenerateScriptPubKey(s2);
			Assert.Equal(p2sh.GetSigOpCount(true), 0U);
			Assert.Equal(p2sh.GetSigOpCount(false), 0U);
			Script scriptSig2 = new Script();
			scriptSig2 = scriptSig2 + OpcodeType.OP_1 + dummy.ToBytes() + dummy.ToBytes() + s2.ToBytes();
			Assert.Equal(p2sh.GetSigOpCount(scriptSig2), 3U);
		}
Example #2
0
        public void SetUnspent(uint160 address, ContractUnspentOutput vin)
        {
            byte[] vinHash = Hashing.HashHelper.Keccak256(vin.ToBytes());
            this.vinCache.Put(vinHash, vin);
            AccountState accountState = this.GetOrCreateAccountState(address);

            accountState.UnspentHash = vinHash;
            this.accountStateCache.Put(address.ToBytes(), accountState);
            this.vinCache.Put(address.ToBytes(), vin);
        }
Example #3
0
        public void SetContractType(uint160 addr, string type)
        {
            AccountState accountState = this.GetOrCreateAccountState(addr);

            accountState.TypeName = type;
            this.accountStateCache.Put(addr.ToBytes(), accountState);
        }
Example #4
0
        public bool Verify(byte[] signature, byte[] data, uint160 nonce)
        {
            byte[]       output    = new byte[256];
            var          msg       = Utils.Combine(nonce.ToBytes(), data);
            Sha512Digest sha512    = new Sha512Digest();
            var          generator = new Mgf1BytesGenerator(sha512);

            generator.Init(new MgfParameters(msg));
            generator.GenerateBytes(output, 0, output.Length);
            var input = new BigInteger(1, output);

            if (input.CompareTo(_Key.Modulus) >= 0)
            {
                return(false);
            }
            if (signature.Length > 256)
            {
                return(false);
            }
            var signatureInt = new BigInteger(1, signature);

            if (signatureInt.CompareTo(_Key.Modulus) >= 0)
            {
                return(false);
            }
            var engine = new RsaBlindedEngine();

            engine.Init(false, _Key);
            return(input.Equals(engine.ProcessBlock(signatureInt)));
        }
Example #5
0
        public AccountState CreateAccount(uint160 addr)
        {
            AccountState state = new AccountState();

            this.accountStateCache.Put(addr.ToBytes(), state);
            return(state);
        }
Example #6
0
        public void SetStorageValue(uint160 addr, byte[] key, byte[] value)
        {
            this.GetOrCreateAccountState(addr);
            ISource <byte[], byte[]> contractStorage = this.storageCache.Get(addr.ToBytes());

            contractStorage.Put(key, value); // TODO: Check if 0
        }
        public void Test_Returns_False_When_Address_Not_Null_Topics_Not_Null()
        {
            var address = new uint160(1);

            var topics = new List <byte[]>
            {
                new byte[] { 0xAA, 0xAA, 0xAA },
                new byte[] { 0xBB, 0xBB, 0xBB },
                new byte[] { 0xCC, 0xCC, 0xCC }
            };

            var bloom = new Bloom();

            bloom.Add(address.ToBytes());

            foreach (var topic in topics)
            {
                bloom.Add(topic);
            }

            var address2 = new uint160(2);

            Assert.False(bloom.Test(address2));
            Assert.False(bloom.Test(address2, new[] { topics[0] }));
            Assert.False(bloom.Test(address2, new[] { topics[1] }));
            Assert.False(bloom.Test(address2, new[] { topics[2] }));
        }
Example #8
0
        public void Test_CatCreation()
        {
            using (PoWMockChain chain = new PoWMockChain(2))
            {
                MockChainNode sender   = chain.Nodes[0];
                MockChainNode receiver = chain.Nodes[1];

                sender.MineBlocks(1);

                ContractCompilationResult compilationResult = ContractCompiler.CompileFile("SmartContracts/ContractCreation.cs");
                Assert.True(compilationResult.Success);

                // Create contract and ensure code exists
                BuildCreateContractTransactionResponse response = sender.SendCreateContractTransaction(compilationResult.Compilation, 0);
                receiver.WaitMempoolCount(1);
                receiver.MineBlocks(2);
                Assert.NotNull(receiver.GetCode(response.NewContractAddress));
                Assert.NotNull(sender.GetCode(response.NewContractAddress));

                // Call contract and ensure internal contract was created.
                BuildCallContractTransactionResponse callResponse = sender.SendCallContractTransaction("CreateCat", response.NewContractAddress, 0);
                receiver.WaitMempoolCount(1);
                receiver.MineBlocks(1);

                Assert.Equal(1, BitConverter.ToInt32(sender.GetStorageValue(response.NewContractAddress, "CatCounter")));
                uint160 lastCreatedCatAddress     = new uint160(sender.GetStorageValue(response.NewContractAddress, "LastCreatedCat"));
                uint160 expectedCreatedCatAddress = this.addressGenerator.GenerateAddress(callResponse.TransactionId, 0);
                Assert.Equal(expectedCreatedCatAddress, lastCreatedCatAddress);

                // Test that the contract address, event name, and logging values are available in the bloom, from internal create.
                var scBlockHeader = receiver.GetLastBlock().Header as SmartContractBlockHeader;
                Assert.True(scBlockHeader.LogsBloom.Test(lastCreatedCatAddress.ToBytes()));
                Assert.True(scBlockHeader.LogsBloom.Test(Encoding.UTF8.GetBytes("CatCreated")));
                Assert.True(scBlockHeader.LogsBloom.Test(BitConverter.GetBytes(0)));
                // And sanity test that a random value is not available in bloom.
                Assert.False(scBlockHeader.LogsBloom.Test(Encoding.UTF8.GetBytes("RandomValue")));

                // Do a create that should transfer all funds sent now.
                decimal amount = 20;
                BuildCallContractTransactionResponse callResponse2 = sender.SendCallContractTransaction("CreateCatWithFunds", response.NewContractAddress, amount);
                receiver.WaitMempoolCount(1);
                receiver.MineBlocks(1);

                // Check created contract has expected balance.
                lastCreatedCatAddress = new uint160(sender.GetStorageValue(response.NewContractAddress, "LastCreatedCat"));
                Assert.Equal(amount * Money.COIN, sender.GetContractBalance(lastCreatedCatAddress.ToBase58Address(sender.CoreNode.FullNode.Network)));

                // Check block has 3 transactions. Coinbase, our tx, and then a condensing tx.
                var block = receiver.GetLastBlock();
                Assert.Equal(3, block.Transactions.Count);
                // Condensing tx has 1 input and 1 output - FROM: real tx. TO: new contract address.
                Assert.Single(block.Transactions[2].Inputs);
                Assert.Single(block.Transactions[2].Outputs);
                Assert.Equal(block.Transactions[1].GetHash(), block.Transactions[2].Inputs[0].PrevOut.Hash); //  References tx above.
                Assert.Equal(amount * Money.COIN, (ulong)block.Transactions[2].Outputs[0].Value);
                Assert.True(block.Transactions[2].Inputs[0].ScriptSig.IsSmartContractSpend());
                Assert.True(block.Transactions[2].Outputs[0].ScriptPubKey.IsSmartContractInternalCall());
            }
        }
Example #9
0
        public void ClearUnspent(uint160 address)
        {
            AccountState accountState = this.GetOrCreateAccountState(address);

            accountState.UnspentHash = null;
            this.accountStateCache.Put(address.ToBytes(), accountState);
            // TODO: Delete old unspent from cache?
        }
Example #10
0
        public void SetCode(uint160 addr, byte[] code)
        {
            byte[] codeHash = Hashing.HashHelper.Keccak256(code);
            this.codeCache.Put(codeHash, code);
            AccountState accountState = this.GetOrCreateAccountState(addr);

            accountState.CodeHash = codeHash;
            this.accountStateCache.Put(addr.ToBytes(), accountState);
        }
Example #11
0
        private AccountState GetOrCreateAccountState(uint160 addr)
        {
            AccountState ret = this.accountStateCache.Get(addr.ToBytes());

            if (ret == null)
            {
                ret = this.CreateAccount(addr);
            }
            return(ret);
        }
        public void Test_Returns_True_When_Address_Not_Null_Topics_Null()
        {
            var address = new uint160(1);

            var bloom = new Bloom();

            bloom.Add(address.ToBytes());

            Assert.True(bloom.Test(address, null));
        }
Example #13
0
        private List <Receipt> SearchReceipts(string contractAddress, string eventName)
        {
            // Build the bytes we can use to check for this event.
            uint160 addressUint160 = contractAddress.ToUint160(this.network);

            byte[] addressBytes = addressUint160.ToBytes();
            byte[] eventBytes   = Encoding.UTF8.GetBytes(eventName);

            // Loop through all headers and check bloom.
            IEnumerable <ChainedHeader> blockHeaders = this.chainIndexer.EnumerateToTip(this.chainIndexer.Genesis);
            List <ChainedHeader>        matches      = new List <ChainedHeader>();

            foreach (ChainedHeader chainedHeader in blockHeaders)
            {
                var scHeader = (ISmartContractBlockHeader)chainedHeader.Header;
                if (scHeader.LogsBloom.Test(addressBytes) && scHeader.LogsBloom.Test(eventBytes)) // TODO: This is really inefficient, should build bloom for query and then compare.
                {
                    matches.Add(chainedHeader);
                }
            }

            // For all matching headers, get the block from local db.
            List <NBitcoin.Block> blocks = new List <NBitcoin.Block>();

            foreach (ChainedHeader chainedHeader in matches)
            {
                blocks.Add(this.blockStore.GetBlock(chainedHeader.HashBlock));
            }

            // For each block, get all receipts, and if they match, add to list to return.
            List <Receipt> receiptResponses = new List <Receipt>();

            foreach (NBitcoin.Block block in blocks)
            {
                foreach (Transaction transaction in block.Transactions)
                {
                    Receipt storedReceipt = this.receiptRepository.Retrieve(transaction.GetHash());
                    if (storedReceipt == null) // not a smart contract transaction. Move to next transaction.
                    {
                        continue;
                    }

                    // Check if address and first topic (event name) match.
                    if (storedReceipt.Logs.Any(x =>
                                               x.Address == addressUint160 && Enumerable.SequenceEqual(x.Topics[0], eventBytes)))
                    {
                        receiptResponses.Add(storedReceipt);
                    }
                }
            }

            return(receiptResponses);
        }
Example #14
0
        public void ContractExecutionResult_RefundDue_AdjustFee()
        {
            var contractAddress = new uint160(1);

            var contractTxData = new ContractTxData(1, 1, (Gas)5000, contractAddress, "ThrowException");
            var sender         = new uint160(2);

            (Money fee, TxOut refund) = this.refundProcessor.Process(contractTxData, new Money(10500), sender, (Gas)950, false);

            Assert.Equal(6450, fee);
            Assert.Equal(sender.ToBytes(), refund.ScriptPubKey.GetDestination(this.network).ToBytes());
            Assert.Equal(4050, refund.Value);
        }
Example #15
0
        public void GetSigOpCount()
        {
            // Test CScript::GetSigOpCount()
            Script s1 = new Script();

            Assert.Equal(s1.GetSigOpCount(false), 0U);
            Assert.Equal(s1.GetSigOpCount(true), 0U);

            uint160 dummy = new uint160(0);

            s1 = s1 + OpcodeType.OP_1 + dummy.ToBytes() + dummy.ToBytes() + OpcodeType.OP_2 + OpcodeType.OP_CHECKMULTISIG;
            Assert.Equal(s1.GetSigOpCount(true), 2U);
            s1 = s1 + OpcodeType.OP_IF + OpcodeType.OP_CHECKSIG + OpcodeType.OP_ENDIF;
            Assert.Equal(s1.GetSigOpCount(true), 3U);
            Assert.Equal(s1.GetSigOpCount(false), 21U);

            var    payToScript = new PayToScriptHashTemplate();
            Script p2sh        = payToScript.GenerateScriptPubKey(s1);
            Script scriptSig   = payToScript.GenerateScriptSig(new[] { (Op)OpcodeType.OP_0 }, s1);

            Assert.Equal(p2sh.GetSigOpCount(scriptSig), 3U);

            var multiSig = new PayToMultiSigTemplate();

            PubKey[] keys = Enumerable.Range(0, 3).Select(_ => new Key(true).PubKey).ToArray();

            Script s2 = multiSig.GenerateScriptPubKey(1, keys);

            Assert.Equal(s2.GetSigOpCount(true), 3U);
            Assert.Equal(s2.GetSigOpCount(false), 20U);

            p2sh = payToScript.GenerateScriptPubKey(s2);
            Assert.Equal(p2sh.GetSigOpCount(true), 0U);
            Assert.Equal(p2sh.GetSigOpCount(false), 0U);
            Script scriptSig2 = new Script();

            scriptSig2 = scriptSig2 + OpcodeType.OP_1 + dummy.ToBytes() + dummy.ToBytes() + s2.ToRawScript();
            Assert.Equal(p2sh.GetSigOpCount(scriptSig2), 3U);
        }
        public void GetSigOpCount()
        {
            // Test CScript::GetSigOpCount()
            var s1 = new Script();

            Assert.Equal(0U, s1.GetSigOpCount(false));
            Assert.Equal(0U, s1.GetSigOpCount(true));

            var dummy = new uint160(0);

            s1 = s1 + OpcodeType.OP_1 + dummy.ToBytes() + dummy.ToBytes() + OpcodeType.OP_2 + OpcodeType.OP_CHECKMULTISIG;
            Assert.Equal(2U, s1.GetSigOpCount(true));
            s1 = s1 + OpcodeType.OP_IF + OpcodeType.OP_CHECKSIG + OpcodeType.OP_ENDIF;
            Assert.Equal(3U, s1.GetSigOpCount(true));
            Assert.Equal(21U, s1.GetSigOpCount(false));

            Script p2sh      = PayToScriptHashTemplate.Instance.GenerateScriptPubKey(s1);
            Script scriptSig = PayToScriptHashTemplate.Instance.GenerateScriptSig(new[] { (Op)OpcodeType.OP_0 }, s1);

            Assert.Equal(3U, p2sh.GetSigOpCount(KnownNetworks.Main, scriptSig));

            PubKey[] keys = Enumerable.Range(0, 3).Select(_ => new Key(true).PubKey).ToArray();

            Script s2 = PayToMultiSigTemplate.Instance.GenerateScriptPubKey(1, keys);

            Assert.Equal(3U, s2.GetSigOpCount(true));
            Assert.Equal(20U, s2.GetSigOpCount(false));

            p2sh = PayToScriptHashTemplate.Instance.GenerateScriptPubKey(s2);
            Assert.Equal(0U, p2sh.GetSigOpCount(true));
            Assert.Equal(0U, p2sh.GetSigOpCount(false));
            var scriptSig2 = new Script();

            scriptSig2 = scriptSig2 + OpcodeType.OP_1 + dummy.ToBytes() + dummy.ToBytes() + s2.ToBytes();
            Assert.Equal(3U, p2sh.GetSigOpCount(KnownNetworks.Main, scriptSig2));
        }
Example #17
0
 public SmartContractReceipt(
     uint256 txHash,
     ulong blockHeight,
     uint160 newContractAddress,
     ulong gasConsumed,
     bool successful,
     Exception exception,
     object returned)
 {
     this.TxHash             = txHash.ToBytes(); // Can't be null as it's used as the key anyhow.
     this.BlockHeight        = blockHeight;
     this.NewContractAddress = newContractAddress?.ToBytes();
     this.GasConsumed        = gasConsumed;
     this.Successful         = successful;
     this.Exception          = exception?.ToString();
     this.Returned           = returned?.ToString();
 }
        /// <summary>
        /// Serializes object to a binary data format.
        /// </summary>
        /// <param name="obj">Object to be serialized.</param>
        /// <returns>Binary data representing the serialized object.</returns>
        internal byte[] Serializer(object obj)
        {
            IBitcoinSerializable serializable = obj as IBitcoinSerializable;

            if (serializable != null)
            {
                return(serializable.ToBytes(network: this.Network));
            }

            uint256 u256 = obj as uint256;

            if (u256 != null)
            {
                return(u256.ToBytes());
            }

            uint160 u160 = obj as uint160;

            if (u160 != null)
            {
                return(u160.ToBytes());
            }

            uint?u32 = obj as uint?;

            if (u32 != null)
            {
                return(u32.ToBytes());
            }

            object[] arr = obj as object[];
            if (arr != null)
            {
                byte[][] serializedItems = new byte[arr.Length][];
                int      itemIndex       = 0;
                foreach (object arrayObject in arr)
                {
                    byte[] serializedObject = this.Serializer(arrayObject);
                    serializedItems[itemIndex] = serializedObject;
                    itemIndex++;
                }
                return(ConcatArrays(serializedItems));
            }

            throw new NotSupportedException();
        }
        /// <summary>
        /// Gets the script used to 'send' an address funds, depending on whether it's a contract or non-contract.
        /// </summary>
        /// <param name="address">The address of the receiver.</param>
        private Script GetTxOutScriptForAddress(uint160 address)
        {
            AccountState accountState = this.stateRepository.GetAccountState(address);

            if (accountState != null)
            {
                var s = new List <byte>
                {
                    (byte)ScOpcodeType.OP_INTERNALCONTRACTTRANSFER
                };
                s.AddRange(address.ToBytes());

                return(new Script(s));
            }

            return(this.CreateScript(address));
        }
Example #20
0
 public byte[] Sign(byte[] data, out uint160 nonce)
 {
     while (true)
     {
         byte[] output = new byte[256];
         nonce = new uint160(RandomUtils.GetBytes(20));
         Sha512Digest sha512    = new Sha512Digest();
         var          msg       = Utils.Combine(nonce.ToBytes(), data);
         var          generator = new Mgf1BytesGenerator(sha512);
         generator.Init(new MgfParameters(msg));
         generator.GenerateBytes(output, 0, output.Length);
         var input = new BigInteger(1, output);
         if (input.CompareTo(_Key.Modulus) >= 0)
         {
             continue;
         }
         var engine = new RsaCoreEngine();
         engine.Init(true, _Key);
         return(engine.ConvertOutput(engine.ProcessBlock(input)));
     }
 }
        public void Test_CatCreation()
        {
            using (MockChain chain = new MockChain(2))
            {
                MockChainNode sender   = chain.Nodes[0];
                MockChainNode receiver = chain.Nodes[1];

                sender.MineBlocks(10);

                SmartContractCompilationResult compilationResult = SmartContractCompiler.CompileFile("SmartContracts/ContractCreation.cs");
                Assert.True(compilationResult.Success);

                // Create contract and ensure code exists
                BuildCreateContractTransactionResponse response = sender.SendCreateContractTransaction(compilationResult.Compilation);
                receiver.WaitMempoolCount(1);
                receiver.MineBlocks(2);
                Assert.NotNull(receiver.GetCode(response.NewContractAddress));
                Assert.NotNull(sender.GetCode(response.NewContractAddress));

                // Call contract and ensure internal contract was created.
                BuildCallContractTransactionResponse callResponse = sender.SendCallContractTransaction("CreateCat", response.NewContractAddress, 0);
                receiver.WaitMempoolCount(1);
                receiver.MineBlocks(1);
                Assert.Equal(1, BitConverter.ToInt32(sender.GetStorageValue(response.NewContractAddress, "CatCounter")));
                uint160 lastCreatedCatAddress     = new uint160(sender.GetStorageValue(response.NewContractAddress, "LastCreatedCat"));
                uint160 expectedCreatedCatAddress = this.addressGenerator.GenerateAddress(callResponse.TransactionId, 0);
                Assert.Equal(expectedCreatedCatAddress, lastCreatedCatAddress);

                // Test that the contract address, event name, and logging values are available in the bloom, from internal create.
                var scBlockHeader = receiver.GetLastBlock().Header as SmartContractBlockHeader;
                Assert.True(scBlockHeader.LogsBloom.Test(lastCreatedCatAddress.ToBytes()));
                Assert.True(scBlockHeader.LogsBloom.Test(Encoding.UTF8.GetBytes("CatCreated")));
                Assert.True(scBlockHeader.LogsBloom.Test(BitConverter.GetBytes(0)));
                // And sanity test that a random value is not available in bloom.
                Assert.False(scBlockHeader.LogsBloom.Test(Encoding.UTF8.GetBytes("RandomValue")));
            }
        }
        /// <summary>
        /// Serializes object to a binary data format.
        /// </summary>
        /// <param name="obj">Object to be serialized.</param>
        /// <returns>Binary data representing the serialized object.</returns>
        internal static byte[] NBitcoinSerialize(object obj)
        {
            IBitcoinSerializable serializable = obj as IBitcoinSerializable;

            if (serializable != null)
            {
                return(serializable.ToBytes());
            }

            uint256 u256 = obj as uint256;

            if (u256 != null)
            {
                return(u256.ToBytes());
            }
            uint160 u160 = obj as uint160;

            if (u160 != null)
            {
                return(u160.ToBytes());
            }
            uint?u32 = obj as uint?;

            if (u32 != null)
            {
                return(u32.ToBytes());
            }

            object[] a = obj as object[];
            if (a != null)
            {
                var result = (from x in a select NBitcoinSerialize(x)).ToArray().SelectMany(x => x).ToArray();
                return(result);
            }

            throw new NotSupportedException();
        }
Example #23
0
 public byte[] ToBytes()
 {
     return(_Id.ToBytes());
 }
Example #24
0
		public AssetId(uint160 value)
			: this(value.ToBytes())
		{
			_value = value;
		}
Example #25
0
 public void Delete(uint160 addr)
 {
     this.accountStateCache.Delete(addr.ToBytes());
     this.storageCache.Delete(addr.ToBytes());
 }
Example #26
0
		public void methods()
		{
			Assert.True(R1L.ToString() == R1L.ToString());
			Assert.True(R2L.ToString() == R2L.ToString());
			Assert.True(OneL.ToString() == OneL.ToString());
			Assert.True(MaxL.ToString() == MaxL.ToString());
			uint256 TmpL = new uint256(R1L);
			Assert.True(TmpL == R1L);
			TmpL.SetHex(R2L.ToString());
			Assert.True(TmpL == R2L);
			TmpL.SetHex(ZeroL.ToString());
			Assert.True(TmpL == 0);
			TmpL.SetHex(HalfL.ToString());
			Assert.True(TmpL == HalfL);

			TmpL.SetHex(R1L.ToString());
			AssertEx.CollectionEquals(R1L.ToBytes(), R1Array);
			AssertEx.CollectionEquals(TmpL.ToBytes(), R1Array);
			AssertEx.CollectionEquals(R2L.ToBytes(), R2Array);
			AssertEx.CollectionEquals(ZeroL.ToBytes(), ZeroArray);
			AssertEx.CollectionEquals(OneL.ToBytes(), OneArray);
			Assert.True(R1L.Size == 32);
			Assert.True(R2L.Size == 32);
			Assert.True(ZeroL.Size == 32);
			Assert.True(MaxL.Size == 32);

			//No sense in .NET
			//Assert.True(R1L.begin() + 32 == R1L.end());
			//Assert.True(R2L.begin() + 32 == R2L.end());
			//Assert.True(OneL.begin() + 32 == OneL.end());
			//Assert.True(MaxL.begin() + 32 == MaxL.end());
			//Assert.True(TmpL.begin() + 32 == TmpL.end());
			Assert.True(R1L.GetLow64() == R1LLow64);
			Assert.True(HalfL.GetLow64() == 0x0000000000000000UL);
			Assert.True(OneL.GetLow64() == 0x0000000000000001UL);
			Assert.True(R1L.GetSerializeSize(0, ProtocolVersion.PROTOCOL_VERSION) == 32);
			Assert.True(ZeroL.GetSerializeSize(0, ProtocolVersion.PROTOCOL_VERSION) == 32);

			MemoryStream ss = new MemoryStream();
			R1L.ReadWrite(ss, true, ProtocolVersion.PROTOCOL_VERSION);
			Assert.True(ArrayToString(ss.ToArray()) == ArrayToString(R1Array));
			ss.Position = 0;
			TmpL.ReadWrite(ss, false, ProtocolVersion.PROTOCOL_VERSION);
			Assert.True(R1L == TmpL);
			ss = new MemoryStream();
			ZeroL.ReadWrite(ss, true, ProtocolVersion.PROTOCOL_VERSION);
			Assert.True(ArrayToString(ss.ToArray()) == ArrayToString(ZeroArray));
			ss.Position = 0;
			TmpL.ReadWrite(ss, false, ProtocolVersion.PROTOCOL_VERSION);
			Assert.True(ZeroL == TmpL);
			ss = new MemoryStream();
			MaxL.ReadWrite(ss, true, ProtocolVersion.PROTOCOL_VERSION);
			Assert.True(ArrayToString(ss.ToArray()) == ArrayToString(MaxArray));
			ss.Position = 0;
			TmpL.ReadWrite(ss, false, ProtocolVersion.PROTOCOL_VERSION);
			Assert.True(MaxL == TmpL);
			ss = new MemoryStream();

			uint160 TmpS = new uint160(R1S);
			Assert.True(TmpS == R1S);
			TmpS.SetHex(R2S.ToString());
			Assert.True(TmpS == R2S);
			TmpS.SetHex(ZeroS.ToString());
			Assert.True(TmpS == 0);
			TmpS.SetHex(HalfS.ToString());
			Assert.True(TmpS == HalfS);

			TmpS.SetHex(R1S.ToString());

			Assert.True(ArrayToString(R1S.ToBytes()) == ArrayToString(R1Array.Take(20).ToArray()));
			Assert.True(ArrayToString(TmpS.ToBytes()) == ArrayToString(R1Array.Take(20).ToArray()));
			Assert.True(ArrayToString(R2S.ToBytes()) == ArrayToString(R2Array.Take(20).ToArray()));
			Assert.True(ArrayToString(ZeroS.ToBytes()) == ArrayToString(ZeroArray.Take(20).ToArray()));
			Assert.True(ArrayToString(OneS.ToBytes()) == ArrayToString(OneArray.Take(20).ToArray()));
			Assert.True(R1S.Size == 20);
			Assert.True(R2S.Size == 20);
			Assert.True(ZeroS.Size == 20);
			Assert.True(MaxS.Size == 20);
			//No sense in .NET
			//Assert.True(R1S.begin() + 20 == R1S.end());
			//Assert.True(R2S.begin() + 20 == R2S.end());
			//Assert.True(OneS.begin() + 20 == OneS.end());
			//Assert.True(MaxS.begin() + 20 == MaxS.end());
			//Assert.True(TmpS.begin() + 20 == TmpS.end());
			Assert.True(R1S.GetLow64() == R1LLow64);
			Assert.True(HalfS.GetLow64() == 0x0000000000000000UL);
			Assert.True(OneS.GetLow64() == 0x0000000000000001UL);
			Assert.True(R1S.GetSerializeSize(0, ProtocolVersion.PROTOCOL_VERSION) == 20);
			Assert.True(ZeroS.GetSerializeSize(0, ProtocolVersion.PROTOCOL_VERSION) == 20);

			R1S.ReadWrite(ss, true, ProtocolVersion.PROTOCOL_VERSION);
			Assert.True(ArrayToString(ss.ToArray()) == ArrayToString(R1Array.Take(20).ToArray()));
			ss.Position = 0;
			TmpS.ReadWrite(ss, false, ProtocolVersion.PROTOCOL_VERSION);
			Assert.True(R1S == TmpS);
			ss = new MemoryStream();
			ZeroS.ReadWrite(ss, true, ProtocolVersion.PROTOCOL_VERSION);
			Assert.True(ArrayToString(ss.ToArray()) == ArrayToString(ZeroArray.Take(20).ToArray()));
			ss.Position = 0;
			TmpS.ReadWrite(ss, false, ProtocolVersion.PROTOCOL_VERSION);
			Assert.True(ZeroS == TmpS);
			ss = new MemoryStream();
			MaxS.ReadWrite(ss, true, ProtocolVersion.PROTOCOL_VERSION);
			Assert.True(ArrayToString(ss.ToArray()) == ArrayToString(MaxArray.Take(20).ToArray()));
			ss.Position = 0;
			TmpS.ReadWrite(ss, false, ProtocolVersion.PROTOCOL_VERSION);
			Assert.True(MaxS == TmpS);
			ss = new MemoryStream();

			//for(int i = 0 ; i < 255 ; ++i)
			//{
			//	Assert.True((OneL << i).GetDouble() == Math.Pow(1.0, i));
			//	if(i < 160)
			//		Assert.True((OneS << i).GetDouble() == Math.Pow(1.0, i));
			//}
			//Assert.True(ZeroL.GetDouble() == 0.0);
			//Assert.True(ZeroS.GetDouble() == 0.0);
			//for(int i = 256 ; i > 53 ; --i)
			//	Assert.True(almostEqual((R1L >> (256 - i)).GetDouble(), Math.Pow(R1Ldouble, i)));
			//for(int i = 160 ; i > 53 ; --i)
			//	Assert.True(almostEqual((R1S >> (160 - i)).GetDouble(), Math.Pow(R1Sdouble, i)));
			//ulong R1L64part = (R1L >> 192).GetLow64();
			//ulong R1S64part = (R1S >> 96).GetLow64();
			//for(int i = 53 ; i > 0 ; --i) // doubles can store all integers in {0,...,2^54-1} exactly
			//{
			//	Assert.True((R1L >> (256 - i)).GetDouble() == (double)(R1L64part >> (64 - i)));
			//	Assert.True((R1S >> (160 - i)).GetDouble() == (double)(R1S64part >> (64 - i)));
			//}
		}
Example #27
0
 public AccountState GetAccountState(uint160 addr)
 {
     return(this.accountStateCache.Get(addr.ToBytes()));
 }
Example #28
0
 public KeyId(uint160 value)
 {
     _DestBytes = value.ToBytes();
 }
 public static Address ToAddress(this uint160 address)
 {
     return(Address.Create(address.ToBytes()));
 }
Example #30
0
        public void methods()
        {
            Assert.True(R1L.GetHex() == R1L.ToString());
            Assert.True(R2L.GetHex() == R2L.ToString());
            Assert.True(OneL.GetHex() == OneL.ToString());
            Assert.True(MaxL.GetHex() == MaxL.ToString());
            uint256 TmpL = new uint256(R1L);

            Assert.True(TmpL == R1L);
            TmpL.SetHex(R2L.ToString());
            Assert.True(TmpL == R2L);
            TmpL.SetHex(ZeroL.ToString());
            Assert.True(TmpL == 0);
            TmpL.SetHex(HalfL.ToString());
            Assert.True(TmpL == HalfL);

            TmpL.SetHex(R1L.ToString());
            AssertEx.CollectionEquals(R1L.ToBytes(), R1Array);
            AssertEx.CollectionEquals(TmpL.ToBytes(), R1Array);
            AssertEx.CollectionEquals(R2L.ToBytes(), R2Array);
            AssertEx.CollectionEquals(ZeroL.ToBytes(), ZeroArray);
            AssertEx.CollectionEquals(OneL.ToBytes(), OneArray);
            Assert.True(R1L.Size == 32);
            Assert.True(R2L.Size == 32);
            Assert.True(ZeroL.Size == 32);
            Assert.True(MaxL.Size == 32);

            //No sense in .NET
            //Assert.True(R1L.begin() + 32 == R1L.end());
            //Assert.True(R2L.begin() + 32 == R2L.end());
            //Assert.True(OneL.begin() + 32 == OneL.end());
            //Assert.True(MaxL.begin() + 32 == MaxL.end());
            //Assert.True(TmpL.begin() + 32 == TmpL.end());
            Assert.True(R1L.GetLow64() == R1LLow64);
            Assert.True(HalfL.GetLow64() == 0x0000000000000000UL);
            Assert.True(OneL.GetLow64() == 0x0000000000000001UL);
            Assert.True(R1L.GetSerializeSize(0, ProtocolVersion.PROTOCOL_VERSION) == 32);
            Assert.True(ZeroL.GetSerializeSize(0, ProtocolVersion.PROTOCOL_VERSION) == 32);

            MemoryStream ss = new MemoryStream();

            R1L.Serialize(ss, 0, ProtocolVersion.PROTOCOL_VERSION);
            Assert.True(ArrayToString(ss.ToArray()) == ArrayToString(R1Array));
            TmpL.Unserialize(ss, 0, ProtocolVersion.PROTOCOL_VERSION);
            Assert.True(R1L == TmpL);
            ss = new MemoryStream();
            ZeroL.Serialize(ss, 0, ProtocolVersion.PROTOCOL_VERSION);
            Assert.True(ArrayToString(ss.ToArray()) == ArrayToString(ZeroArray));
            ss.Position = 0;
            TmpL.Unserialize(ss, 0, ProtocolVersion.PROTOCOL_VERSION);
            Assert.True(ZeroL == TmpL);
            ss = new MemoryStream();
            MaxL.Serialize(ss, 0, ProtocolVersion.PROTOCOL_VERSION);
            Assert.True(ArrayToString(ss.ToArray()) == ArrayToString(MaxArray));
            ss.Position = 0;
            TmpL.Unserialize(ss, 0, ProtocolVersion.PROTOCOL_VERSION);
            Assert.True(MaxL == TmpL);
            ss = new MemoryStream();

            Assert.True(R1S.GetHex() == R1S.ToString());
            Assert.True(R2S.GetHex() == R2S.ToString());
            Assert.True(OneS.GetHex() == OneS.ToString());
            Assert.True(MaxS.GetHex() == MaxS.ToString());
            uint160 TmpS = new uint160(R1S);

            Assert.True(TmpS == R1S);
            TmpS.SetHex(R2S.ToString());
            Assert.True(TmpS == R2S);
            TmpS.SetHex(ZeroS.ToString());
            Assert.True(TmpS == 0);
            TmpS.SetHex(HalfS.ToString());
            Assert.True(TmpS == HalfS);

            TmpS.SetHex(R1S.ToString());

            Assert.True(ArrayToString(R1S.ToBytes()) == ArrayToString(R1Array.Take(20).ToArray()));
            Assert.True(ArrayToString(TmpS.ToBytes()) == ArrayToString(R1Array.Take(20).ToArray()));
            Assert.True(ArrayToString(R2S.ToBytes()) == ArrayToString(R2Array.Take(20).ToArray()));
            Assert.True(ArrayToString(ZeroS.ToBytes()) == ArrayToString(ZeroArray.Take(20).ToArray()));
            Assert.True(ArrayToString(OneS.ToBytes()) == ArrayToString(OneArray.Take(20).ToArray()));
            Assert.True(R1S.Size == 20);
            Assert.True(R2S.Size == 20);
            Assert.True(ZeroS.Size == 20);
            Assert.True(MaxS.Size == 20);
            //No sense in .NET
            //Assert.True(R1S.begin() + 20 == R1S.end());
            //Assert.True(R2S.begin() + 20 == R2S.end());
            //Assert.True(OneS.begin() + 20 == OneS.end());
            //Assert.True(MaxS.begin() + 20 == MaxS.end());
            //Assert.True(TmpS.begin() + 20 == TmpS.end());
            Assert.True(R1S.GetLow64() == R1LLow64);
            Assert.True(HalfS.GetLow64() == 0x0000000000000000UL);
            Assert.True(OneS.GetLow64() == 0x0000000000000001UL);
            Assert.True(R1S.GetSerializeSize(0, ProtocolVersion.PROTOCOL_VERSION) == 20);
            Assert.True(ZeroS.GetSerializeSize(0, ProtocolVersion.PROTOCOL_VERSION) == 20);

            R1S.Serialize(ss, 0, ProtocolVersion.PROTOCOL_VERSION);
            Assert.True(ArrayToString(ss.ToArray()) == ArrayToString(R1Array.Take(20).ToArray()));
            ss.Position = 0;
            TmpS.Unserialize(ss, 0, ProtocolVersion.PROTOCOL_VERSION);
            Assert.True(R1S == TmpS);
            ss = new MemoryStream();
            ZeroS.Serialize(ss, 0, ProtocolVersion.PROTOCOL_VERSION);
            Assert.True(ArrayToString(ss.ToArray()) == ArrayToString(ZeroArray.Take(20).ToArray()));
            ss.Position = 0;
            TmpS.Unserialize(ss, 0, ProtocolVersion.PROTOCOL_VERSION);
            Assert.True(ZeroS == TmpS);
            ss = new MemoryStream();
            MaxS.Serialize(ss, 0, ProtocolVersion.PROTOCOL_VERSION);
            Assert.True(ArrayToString(ss.ToArray()) == ArrayToString(MaxArray.Take(20).ToArray()));
            ss.Position = 0;
            TmpS.Unserialize(ss, 0, ProtocolVersion.PROTOCOL_VERSION);
            Assert.True(MaxS == TmpS);
            ss = new MemoryStream();

            //for(int i = 0 ; i < 255 ; ++i)
            //{
            //	Assert.True((OneL << i).GetDouble() == Math.Pow(1.0, i));
            //	if(i < 160)
            //		Assert.True((OneS << i).GetDouble() == Math.Pow(1.0, i));
            //}
            //Assert.True(ZeroL.GetDouble() == 0.0);
            //Assert.True(ZeroS.GetDouble() == 0.0);
            //for(int i = 256 ; i > 53 ; --i)
            //	Assert.True(almostEqual((R1L >> (256 - i)).GetDouble(), Math.Pow(R1Ldouble, i)));
            //for(int i = 160 ; i > 53 ; --i)
            //	Assert.True(almostEqual((R1S >> (160 - i)).GetDouble(), Math.Pow(R1Sdouble, i)));
            //ulong R1L64part = (R1L >> 192).GetLow64();
            //ulong R1S64part = (R1S >> 96).GetLow64();
            //for(int i = 53 ; i > 0 ; --i) // doubles can store all integers in {0,...,2^54-1} exactly
            //{
            //	Assert.True((R1L >> (256 - i)).GetDouble() == (double)(R1L64part >> (64 - i)));
            //	Assert.True((R1S >> (160 - i)).GetDouble() == (double)(R1S64part >> (64 - i)));
            //}
        }
Example #31
0
 public AssetId(uint160 value)
     : this(value.ToBytes())
 {
     _value = value;
 }
Example #32
0
        public byte[] GetStorageValue(uint160 addr, byte[] key)
        {
            AccountState accountState = this.GetAccountState(addr);

            return(accountState == null ? null : this.storageCache.Get(addr.ToBytes()).Get(key));
        }