コード例 #1
0
ファイル: uint256_tests.cs プロジェクト: xcrash/NBitcoin
		public uint256_tests()
		{
			R1Array = ToBytes("\x9c\x52\x4a\xdb\xcf\x56\x11\x12\x2b\x29\x12\x5e\x5d\x35\xd2\xd2\x22\x81\xaa\xb5\x33\xf0\x08\x32\xd5\x56\xb1\xf9\xea\xe5\x1d\x7d");
			R1L = new uint256(R1Array);
			NegR1L = ~R1L;
			R1S = new uint160(R1Array.Take(20).ToArray());
			NegR1S = ~R1S;
			NegR1Array = NegR1L.ToBytes();

			R2Array = ToBytes("\x70\x32\x1d\x7c\x47\xa5\x6b\x40\x26\x7e\x0a\xc3\xa6\x9c\xb6\xbf\x13\x30\x47\xa3\x19\x2d\xda\x71\x49\x13\x72\xf0\xb4\xca\x81\xd7");
			R2L = new uint256(R2Array);
			NegR2L = ~R2L;
			R2S = new uint160(R2Array.Take(20).ToArray());
			NegR2S = ~R2S;
			NegR2Array = NegR2L.ToBytes();

			ZeroArray = ToBytes("\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00");
			ZeroL = new uint256(ZeroArray);
			ZeroS = new uint160(ZeroArray.Take(20).ToArray());

			OneArray = ToBytes("\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00");
			OneL = new uint256(OneArray);
			OneS = new uint160(OneArray.Take(20).ToArray());

			MaxArray = ToBytes("\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff");
			MaxL = new uint256(MaxArray);
			MaxS = new uint160(MaxArray.Take(20).ToArray());

			HalfL = OneL << 255;
			HalfS = OneS << 159;
		}
コード例 #2
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);
		}
コード例 #3
0
ファイル: PackerTests.cs プロジェクト: lontivero/BitcoinLite
        public void BigEndian()
        {
            var big = Packer.BigEndian;
            var arr = new byte[] { 0x01, 0x02, 0x03, 0x04, 0xff };
            CollectionAssert.AreEqual(arr.Reverse(), big.GetBytes(arr));

            // booleans
            CollectionAssert.AreEqual(Hex2Bytes("01"), big.GetBytes(true));
            CollectionAssert.AreEqual(Hex2Bytes("00"), big.GetBytes(false));
            Assert.AreEqual(false, big.ToBoolean(Hex2Bytes("00"), 0));
            Assert.AreEqual(true, big.ToBoolean(Hex2Bytes("01"), 0));

            // chars
            CollectionAssert.AreEqual(Hex2Bytes("0061").Reverse(), big.GetBytes('a'));
            Assert.AreEqual('a', big.ToChar(Hex2Bytes("0061").Reverse().ToArray(), 0));

            // shorts
            CollectionAssert.AreEqual(Hex2Bytes("3039").Reverse(), big.GetBytes((ushort)12345));
            CollectionAssert.AreEqual(Hex2Bytes("3039").Reverse(), big.GetBytes((short)12345));
            CollectionAssert.AreEqual(Hex2Bytes("CFC7").Reverse(), big.GetBytes((short)-12345));
            Assert.AreEqual(12345, big.ToUInt16(Hex2Bytes("3039").Reverse().ToArray(), 0));
            Assert.AreEqual(12345, big.ToInt16(Hex2Bytes("3039").Reverse().ToArray(), 0));
            Assert.AreEqual(-12345, big.ToInt16(Hex2Bytes("CFC7").Reverse().ToArray(), 0));

            // ints
            CollectionAssert.AreEqual(Hex2Bytes("0034B59F").Reverse(), big.GetBytes((uint)3454367));
            CollectionAssert.AreEqual(Hex2Bytes("0034B59F").Reverse(), big.GetBytes(3454367));
            CollectionAssert.AreEqual(Hex2Bytes("FFCB4A61").Reverse(), big.GetBytes(-3454367));
            Assert.AreEqual(3454367, big.ToUInt32(Hex2Bytes("0034B59F").Reverse().ToArray(), 0));
            Assert.AreEqual(3454367, big.ToInt32(Hex2Bytes("0034B59F").Reverse().ToArray(), 0));
            Assert.AreEqual(-3454367, big.ToInt32(Hex2Bytes("FFCB4A61").Reverse().ToArray(), 0));

            // long
            CollectionAssert.AreEqual(Hex2Bytes("000000506DA33CD5").Reverse(), big.GetBytes((ulong)345436798165));
            CollectionAssert.AreEqual(Hex2Bytes("000000506DA33CD5").Reverse(), big.GetBytes(345436798165));
            CollectionAssert.AreEqual(Hex2Bytes("FFFFFFAF925CC32B").Reverse(), big.GetBytes(-345436798165));
            Assert.AreEqual(345436798165, big.ToUInt64(Hex2Bytes("000000506DA33CD5").Reverse().ToArray(), 0));
            Assert.AreEqual(345436798165, big.ToInt64(Hex2Bytes("000000506DA33CD5").Reverse().ToArray(), 0));
            Assert.AreEqual(-345436798165, big.ToInt64(Hex2Bytes("FFFFFFAF925CC32B").Reverse().ToArray(), 0));

            var u256 = new uint256(345436798165);
            var u256b = Hex2Bytes("000000000000000000000000000000000000000000000000000000506da33cd5");
            CollectionAssert.AreEqual(u256b.Reverse(), big.GetBytes(u256));
            Assert.AreEqual(u256, big.ToUInt256(u256b.Reverse().ToArray(), 0));

            var u160 = new uint160(345436798165);
            var u160b = Hex2Bytes("000000000000000000000000000000506da33cd5");
            CollectionAssert.AreEqual(u160b.Reverse(), big.GetBytes(u160));
            Assert.AreEqual(u160, big.ToUInt160(u160b.Reverse().ToArray(), 0));
        }
コード例 #4
0
        public void SendAndReceiveSmartContractTransactionsOnPosNetwork()
        {
            using (SmartContractNodeBuilder builder = SmartContractNodeBuilder.Create(this))
            {
                CoreNode scSender   = builder.CreateSmartContractPosNode().WithWallet().Start();
                CoreNode scReceiver = builder.CreateSmartContractPosNode().WithWallet().Start();

                var callDataSerializer = new CallDataSerializer(new ContractPrimitiveSerializer(scSender.FullNode.Network));

                var       maturity      = (int)scSender.FullNode.Network.Consensus.CoinbaseMaturity;
                HdAddress senderAddress = TestHelper.MineBlocks(scSender, maturity + 5).AddressUsed;

                // The mining should add coins to the wallet.
                var total = scSender.FullNode.WalletManager().GetSpendableTransactionsInWallet(WalletName).Sum(s => s.Transaction.Amount);
                Assert.Equal(Money.COIN * 6 * 50, total);

                // Create a token contract
                ulong gasPrice  = 1;
                int   vmVersion = 1;
                Gas   gasLimit  = (Gas)5000;
                ContractCompilationResult compilationResult = ContractCompiler.CompileFile("SmartContracts/TransferTestPos.cs");
                Assert.True(compilationResult.Success);

                var contractTxData = new ContractTxData(vmVersion, gasPrice, gasLimit, compilationResult.Compilation);

                var contractCreateScript = new Script(callDataSerializer.Serialize(contractTxData));
                var txBuildContext       = new TransactionBuildContext(scSender.FullNode.Network)
                {
                    AccountReference = new WalletAccountReference(WalletName, AccountName),
                    ChangeAddress    = senderAddress,
                    MinConfirmations = maturity,
                    FeeType          = FeeType.High,
                    WalletPassword   = Password,
                    Recipients       = new[] { new Recipient {
                                                   Amount = 0, ScriptPubKey = contractCreateScript
                                               } }.ToList()
                };

                // Build the transfer contract transaction
                var transferContractTransaction = BuildTransferContractTransaction(scSender, txBuildContext);

                // Add the smart contract transaction to the mempool to be mined.
                scSender.AddToStratisMempool(transferContractTransaction);

                // Ensure the smart contract transaction is in the mempool.
                TestHelper.WaitLoop(() => scSender.CreateRPCClient().GetRawMempool().Length > 0);

                // Mine the token transaction and wait for it sync
                TestHelper.MineBlocks(scSender, 1);

                // Sync to the receiver node
                TestHelper.ConnectAndSync(scSender, scReceiver);

                // Ensure that boths nodes has the contract
                IStateRepositoryRoot senderState      = scSender.FullNode.NodeService <IStateRepositoryRoot>();
                IStateRepositoryRoot receiverState    = scReceiver.FullNode.NodeService <IStateRepositoryRoot>();
                IAddressGenerator    addressGenerator = scSender.FullNode.NodeService <IAddressGenerator>();

                uint160 tokenContractAddress = addressGenerator.GenerateAddress(transferContractTransaction.GetHash(), 0);
                Assert.NotNull(senderState.GetCode(tokenContractAddress));
                Assert.NotNull(receiverState.GetCode(tokenContractAddress));
                scSender.FullNode.MempoolManager().Clear();

                // Create a transfer token contract
                compilationResult = ContractCompiler.CompileFile("SmartContracts/TransferTestPos.cs");
                Assert.True(compilationResult.Success);
                contractTxData       = new ContractTxData(vmVersion, gasPrice, gasLimit, compilationResult.Compilation);
                contractCreateScript = new Script(callDataSerializer.Serialize(contractTxData));
                txBuildContext       = new TransactionBuildContext(scSender.FullNode.Network)
                {
                    AccountReference = new WalletAccountReference(WalletName, AccountName),
                    ChangeAddress    = senderAddress,
                    MinConfirmations = maturity,
                    FeeType          = FeeType.High,
                    WalletPassword   = Password,
                    Recipients       = new[] { new Recipient {
                                                   Amount = 0, ScriptPubKey = contractCreateScript
                                               } }.ToList()
                };

                // Build the transfer contract transaction
                transferContractTransaction = BuildTransferContractTransaction(scSender, txBuildContext);

                // Add the smart contract transaction to the mempool to be mined.
                scSender.AddToStratisMempool(transferContractTransaction);

                // Wait for the token transaction to be picked up by the mempool
                TestHelper.WaitLoop(() => scSender.CreateRPCClient().GetRawMempool().Length > 0);
                TestHelper.MineBlocks(scSender, 1);

                // Ensure both nodes are synced with each other
                TestHelper.WaitLoop(() => TestHelper.AreNodesSynced(scReceiver, scSender));

                tokenContractAddress = addressGenerator.GenerateAddress(transferContractTransaction.GetHash(), 0); // nonce is 0 for user contract creation.
                Assert.NotNull(senderState.GetCode(tokenContractAddress));
                Assert.NotNull(receiverState.GetCode(tokenContractAddress));
                scSender.FullNode.MempoolManager().Clear();

                // Create a call contract transaction which will transfer funds
                contractTxData = new ContractTxData(1, gasPrice, gasLimit, tokenContractAddress, "Test");
                Script contractCallScript = new Script(callDataSerializer.Serialize(contractTxData));
                txBuildContext = new TransactionBuildContext(scSender.FullNode.Network)
                {
                    AccountReference = new WalletAccountReference(WalletName, AccountName),
                    ChangeAddress    = senderAddress,
                    MinConfirmations = maturity,
                    FeeType          = FeeType.High,
                    WalletPassword   = Password,
                    Recipients       = new[] { new Recipient {
                                                   Amount = 1000, ScriptPubKey = contractCallScript
                                               } }.ToList()
                };

                // Build the transfer contract transaction
                var callContractTransaction = BuildTransferContractTransaction(scSender, txBuildContext);

                // Add the smart contract transaction to the mempool to be mined.
                scSender.AddToStratisMempool(callContractTransaction);

                // Wait for the token transaction to be picked up by the mempool
                TestHelper.WaitLoop(() => scSender.CreateRPCClient().GetRawMempool().Length > 0);
                TestHelper.MineBlocks(scSender, 1);

                // Ensure the nodes are synced
                TestHelper.WaitLoop(() => TestHelper.AreNodesSynced(scReceiver, scSender));

                // The balance should now reflect the transfer
                Assert.Equal((ulong)900, senderState.GetCurrentBalance(tokenContractAddress));
            }
        }
コード例 #5
0
        public IActionResult GetContractInfo([FromQuery] string txHash)
        {
            try
            {
                uint256 txHashNum = new uint256(txHash);
                Receipt receipt   = this.receiptRepository.Retrieve(txHashNum);

                if (receipt == null)
                {
                    return(null);
                }

                uint160 address = receipt.NewContractAddress ?? receipt.To;

                string  typeName     = null;
                byte[]  contractCode = null;
                uint256 codeHash     = null;
                string  csharpCode   = null;
                ulong   balance      = 0;

                if (address != null)
                {
                    IStateRepositoryRoot stateAtHeight = this.stateRoot.GetSnapshotTo(receipt.PostState.ToBytes());
                    AccountState         accountState  = stateAtHeight.GetAccountState(address);

                    if (accountState != null)
                    {
                        typeName = accountState.TypeName;
                        balance  = stateAtHeight.GetCurrentBalance(address);

                        if (receipt.NewContractAddress != null)
                        {
                            codeHash     = new uint256(accountState.CodeHash);
                            contractCode = this.stateRoot.GetCode(receipt.NewContractAddress);
                            Result <string> sourceResult = this.contractDecompiler.GetSource(contractCode);
                            csharpCode = sourceResult.IsSuccess ? sourceResult.Value : sourceResult.Error;
                        }
                    }
                    else
                    {
                        typeName = this.stateRoot.GetAccountState(address)?.TypeName;
                    }
                }

                List <LogResponse> logResponses = new List <LogResponse>();

                if (receipt.Logs.Any())
                {
                    var deserializer = new ApiLogDeserializer(this.primitiveSerializer, this.network, this.stateRoot, this.contractAssemblyCache);

                    logResponses = deserializer.MapLogResponses(receipt.Logs);
                }

                var logEnrichment = contractEnrichmentFactory.GetLogEnrichment(typeName);

                logEnrichment?.EnrichLogs(receipt, logResponses);

                return(this.Json(new ContractReceiptResponse(receipt, logResponses, this.network)
                {
                    ContractCodeType = typeName,
                    ContractBalance = balance,
                    ContractCodeHash = codeHash?.ToString(),
                    ContractBytecode = contractCode?.ToHexString(),
                    ContractCSharp = csharpCode
                }));
            }
            catch (Exception e)
            {
                this.logger.LogError("Exception occurred: {0}", e.ToString());
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()));
            }
        }
コード例 #6
0
        private ulong FetchNoRefundBlockCount(uint160 contractAddress)
        {
            var serializedValue = _stateRepositoryRoot.GetStorageValue(contractAddress, _serializer.Serialize("NoRefundBlockCount"));

            return(_serializer.ToUInt64(serializedValue));
        }
コード例 #7
0
        private bool HasOpenSale(uint160 contractAddress)
        {
            var endOfSale = FetchEndOfSale(contractAddress);

            return(endOfSale != default && (ulong)_consensusManager.Tip.Height < endOfSale);
        }
コード例 #8
0
        private Ticket[] RetrieveTickets(uint160 contractAddress)
        {
            var serializedValue = _stateRepositoryRoot.GetStorageValue(contractAddress, _serializer.Serialize(nameof(TicketContract.Tickets)));

            return(_serializer.ToArray <Ticket>(serializedValue));
        }
コード例 #9
0
 public CScriptID(uint160 pubKeyHash)
     : base(pubKeyHash)
 {
 }
コード例 #10
0
 public ulong GetBalance(uint160 address)
 {
     return(this.repository.GetCurrentBalance(address)
            + this.txAmount
            + this.GetPendingBalance(address));
 }
コード例 #11
0
 protected BaseMessage(uint160 from, ulong amount, Gas gasLimit)
 {
     this.From     = from;
     this.Amount   = amount;
     this.GasLimit = gasLimit;
 }
コード例 #12
0
ファイル: TransferInfo.cs プロジェクト: georgepinca/src
 public TransferInfo(uint160 from, uint160 to, ulong value)
 {
     this.From  = from;
     this.To    = to;
     this.Value = value;
 }
コード例 #13
0
ファイル: uint256_tests.cs プロジェクト: xcrash/NBitcoin
		private void CHECKBITWISEOPERATOR(string a, string b, char op)
		{
			var map = new object[][]{
								new object[]{'|',"BitwiseOr",new Func<byte,byte,byte>((aa,bb)=>(byte)(aa | bb))},
								new object[]{'^',"ExclusiveOr",new Func<byte,byte,byte>((aa,bb)=>(byte)(aa ^ bb))},
								new object[]{'&',"BitwiseAnd",new Func<byte,byte,byte>((aa,bb)=>(byte)(aa & bb))},
							}.ToDictionary(k => (char)k[0], k => new
							{
								Name = (string)k[1],
								ByteFunc = (Func<byte, byte, byte>)k[2]
							});


			var aL = (uint256)this.GetType().GetField(a + "L", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(this);
			var aS = (uint160)this.GetType().GetField(a + "S", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(this);
			var aArray = (byte[])this.GetType().GetField(a + "Array", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(this);

			var bL = (uint256)this.GetType().GetField(b + "L", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(this);
			var bS = (uint160)this.GetType().GetField(b + "S", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(this);
			var bArray = (byte[])this.GetType().GetField(b + "Array", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(this);

			var mS = typeof(uint160).GetMethod("op_" + map[op].Name);
			var mL = typeof(uint256).GetMethod("op_" + map[op].Name);


			byte[] arr = new byte[32];
			for(int i = 0 ; i < arr.Length ; i++)
			{
				arr[i] = map[op].ByteFunc(aArray[i], bArray[i]);
			}

			var actual = (uint256)mL.Invoke(null, new object[] { aL, bL });
			var expected = new uint256(arr);
			Assert.True(expected == actual);

			arr = new byte[20];
			for(int i = 0 ; i < arr.Length ; i++)
			{
				arr[i] = map[op].ByteFunc(aArray[i], bArray[i]);
			}

			var actual1 = (uint160)mS.Invoke(null, new object[] { aS, bS });
			var expected1 = new uint160(arr);
			Assert.True(expected1 == actual1);
		}
コード例 #14
0
ファイル: uint256_tests.cs プロジェクト: xcrash/NBitcoin
		public void plusMinus()
		{
			uint256 TmpL = 0;
			Assert.True(R1L + R2L == uint256.Parse(R1LplusR2L));
			TmpL += R1L;
			Assert.True(TmpL == R1L);
			TmpL += R2L;
			Assert.True(TmpL == R1L + R2L);
			Assert.True(OneL + MaxL == ZeroL);
			Assert.True(MaxL + OneL == ZeroL);
			for(int i = 1 ; i < 256 ; ++i)
			{
				Assert.True((MaxL >> i) + OneL == (HalfL >> (i - 1)));
				Assert.True(OneL + (MaxL >> i) == (HalfL >> (i - 1)));
				TmpL = (MaxL >> i);
				TmpL += OneL;
				Assert.True(TmpL == (HalfL >> (i - 1)));
				TmpL = (MaxL >> i);
				TmpL += 1;
				Assert.True(TmpL == (HalfL >> (i - 1)));
				TmpL = (MaxL >> i);
				Assert.True(TmpL++ == (MaxL >> i));
				Assert.True(TmpL == (HalfL >> (i - 1)));
			}
			Assert.True(new uint256(0xbedc77e27940a7UL) + 0xee8d836fce66fbUL == new uint256(0xbedc77e27940a7UL + 0xee8d836fce66fbUL));
			TmpL = new uint256(0xbedc77e27940a7UL);
			TmpL += 0xee8d836fce66fbUL;
			Assert.True(TmpL == new uint256(0xbedc77e27940a7UL + 0xee8d836fce66fbUL));
			TmpL -= 0xee8d836fce66fbUL;
			Assert.True(TmpL == 0xbedc77e27940a7UL);
			TmpL = R1L;
			Assert.True(++TmpL == R1L + 1);

			Assert.True(R1L - (-R2L) == R1L + R2L);
			Assert.True(R1L - (-OneL) == R1L + OneL);
			Assert.True(R1L - OneL == R1L + (-OneL));
			for(int i = 1 ; i < 256 ; ++i)
			{
				Assert.True((MaxL >> i) - (-OneL) == (HalfL >> (i - 1)));
				Assert.True((HalfL >> (i - 1)) - OneL == (MaxL >> i));
				TmpL = (HalfL >> (i - 1));
				Assert.True(TmpL-- == (HalfL >> (i - 1)));
				Assert.True(TmpL == (MaxL >> i));
				TmpL = (HalfL >> (i - 1));
				Assert.True(--TmpL == (MaxL >> i));
			}
			TmpL = R1L;
			Assert.True(--TmpL == R1L - 1);

			// 160-bit; copy-pasted
			uint160 TmpS = 0;
			Assert.True(R1S + R2S == uint160.Parse(R1LplusR2L));
			TmpS += R1S;
			Assert.True(TmpS == R1S);
			TmpS += R2S;
			Assert.True(TmpS == R1S + R2S);
			Assert.True(OneS + MaxS == ZeroS);
			Assert.True(MaxS + OneS == ZeroS);
			for(int i = 1 ; i < 160 ; ++i)
			{
				Assert.True((MaxS >> i) + OneS == (HalfS >> (i - 1)));
				Assert.True(OneS + (MaxS >> i) == (HalfS >> (i - 1)));
				TmpS = (MaxS >> i);
				TmpS += OneS;
				Assert.True(TmpS == (HalfS >> (i - 1)));
				TmpS = (MaxS >> i);
				TmpS += 1;
				Assert.True(TmpS == (HalfS >> (i - 1)));
				TmpS = (MaxS >> i);
				Assert.True(TmpS++ == (MaxS >> i));
				Assert.True(TmpS == (HalfS >> (i - 1)));
			}
			Assert.True(new uint160(0xbedc77e27940a7UL) + 0xee8d836fce66fbUL == new uint160(0xbedc77e27940a7UL + 0xee8d836fce66fbUL));
			TmpS = new uint160(0xbedc77e27940a7UL);
			TmpS += 0xee8d836fce66fbUL;
			Assert.True(TmpS == new uint160(0xbedc77e27940a7UL + 0xee8d836fce66fbUL));
			TmpS -= 0xee8d836fce66fbUL;
			Assert.True(TmpS == 0xbedc77e27940a7UL);
			TmpS = R1S;
			Assert.True(++TmpS == R1S + 1);

			Assert.True(R1S - (-R2S) == R1S + R2S);
			Assert.True(R1S - (-OneS) == R1S + OneS);
			Assert.True(R1S - OneS == R1S + (-OneS));
			for(int i = 1 ; i < 160 ; ++i)
			{
				Assert.True((MaxS >> i) - (-OneS) == (HalfS >> (i - 1)));
				Assert.True((HalfS >> (i - 1)) - OneS == (MaxS >> i));
				TmpS = (HalfS >> (i - 1));
				Assert.True(TmpS-- == (HalfS >> (i - 1)));
				Assert.True(TmpS == (MaxS >> i));
				TmpS = (HalfS >> (i - 1));
				Assert.True(--TmpS == (MaxS >> i));
			}
			TmpS = R1S;
			Assert.True(--TmpS == R1S - 1);
		}
コード例 #15
0
ファイル: uint256_tests.cs プロジェクト: xcrash/NBitcoin
		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)));
			//}
		}
コード例 #16
0
 public InternalCallMessage(uint160 to, uint160 from, ulong amount, Gas gasLimit, MethodCall methodCall)
     : base(to, from, amount, gasLimit, methodCall)
 {
 }
コード例 #17
0
        public ILocalExecutionResult Execute(ulong blockHeight, uint160 sender, Money txOutValue, ContractTxData callData)
        {
            bool creation = callData.IsCreateContract;

            var block = new Block(
                blockHeight,
                Address.Zero
                );

            ChainedHeader chainedHeader = this.chainIndexer.GetHeader((int)blockHeight);

            var scHeader = chainedHeader?.Header as ISmartContractBlockHeader;

            uint256 hashStateRoot = scHeader?.HashStateRoot ?? new uint256("21B463E3B52F6201C0AD6C991BE0485B6EF8C092E64583FFA655CC1B171FE856"); // StateRootEmptyTrie

            IStateRepositoryRoot stateAtHeight = this.stateRoot.GetSnapshotTo(hashStateRoot.ToBytes());

            IState state = this.stateFactory.Create(
                stateAtHeight.StartTracking(),
                block,
                txOutValue,
                new uint256());

            StateTransitionResult result;
            IState newState = state.Snapshot();

            if (creation)
            {
                var message = new ExternalCreateMessage(
                    sender,
                    txOutValue,
                    callData.GasLimit,
                    callData.ContractExecutionCode,
                    callData.MethodParameters
                    );

                result = this.stateProcessor.Apply(newState, message);
            }
            else
            {
                var message = new ExternalCallMessage(
                    callData.ContractAddress,
                    sender,
                    txOutValue,
                    callData.GasLimit,
                    new MethodCall(callData.MethodName, callData.MethodParameters)
                    );

                result = this.stateProcessor.Apply(newState, message);
            }

            var executionResult = new LocalExecutionResult
            {
                ErrorMessage      = result.Error?.GetErrorMessage(),
                Revert            = result.IsFailure,
                GasConsumed       = result.GasConsumed,
                Return            = result.Success?.ExecutionResult,
                InternalTransfers = newState.InternalTransfers.ToList(),
                Logs      = newState.GetLogs(this.contractPrimitiveSerializer),
                StateRoot = newState.ContractState
            };

            return(executionResult);
        }
コード例 #18
0
 /// <summary>
 /// Instantiate a new PersistentState instance. Each PersistentState object represents
 /// a slice of state for a particular contract address.
 /// </summary>
 /// <param name="persistenceStrategy"></param>
 /// <param name="contractAddress"></param>
 /// <param name="network"></param>
 public PersistentState(IPersistenceStrategy persistenceStrategy, uint160 contractAddress, Network network)
 {
     this.persistenceStrategy = persistenceStrategy;
     this.ContractAddress     = contractAddress;
     this.network             = network;
 }
コード例 #19
0
 public CKeyID(uint160 pubKeyHash)
     : base(pubKeyHash)
 {
 }
コード例 #20
0
 public ContractTransferMessage(uint160 to, uint160 from, ulong amount, RuntimeObserver.Gas gasLimit)
     : base(to, from, amount, gasLimit, MethodCall.Receive())
 {
 }
コード例 #21
0
        private bool RetrieveIdentityVerificationPolicy(uint160 contractAddress)
        {
            var serializedIdentityVerificationPolicy = _stateRepositoryRoot.GetStorageValue(contractAddress, _serializer.Serialize("RequireIdentityVerification"));

            return(_serializer.ToBool(serializedIdentityVerificationPolicy));
        }
コード例 #22
0
        public void InternalTransfer_ToContractAddress()
        {
            // Ensure fixture is funded.
            this.mockChain.MineBlocks(1);

            // Deploy contract to send to
            ContractCompilationResult receiveCompilationResult = ContractCompiler.CompileFile("SmartContracts/BasicReceive.cs");

            Assert.True(receiveCompilationResult.Success);
            BuildCreateContractTransactionResponse receiveResponse = this.node1.SendCreateContractTransaction(receiveCompilationResult.Compilation, 0);

            this.mockChain.WaitAllMempoolCount(1);
            this.mockChain.MineBlocks(1);
            Assert.NotNull(this.node1.GetCode(receiveResponse.NewContractAddress));

            // Deploy contract to send from
            ContractCompilationResult compilationResult = ContractCompiler.CompileFile("SmartContracts/BasicTransfer.cs");

            Assert.True(compilationResult.Success);
            BuildCreateContractTransactionResponse preResponse = this.node1.SendCreateContractTransaction(compilationResult.Compilation, 0);

            this.mockChain.WaitAllMempoolCount(1);
            this.mockChain.MineBlocks(1);
            Assert.NotNull(this.node1.GetCode(preResponse.NewContractAddress));

            decimal amount = 25;
            Money   senderBalanceBefore = this.node1.WalletSpendableBalance;
            uint256 currentHash         = this.node1.GetLastBlock().GetHash();

            // Send amount to contract, which will send to contract address
            string[] parameters = new string[] { string.Format("{0}#{1}", (int)MethodParameterDataType.Address, receiveResponse.NewContractAddress) };
            BuildCallContractTransactionResponse response = this.node1.SendCallContractTransaction(
                nameof(BasicTransfer.SendToAddress),
                preResponse.NewContractAddress,
                amount,
                parameters);

            this.mockChain.WaitAllMempoolCount(1);
            this.mockChain.MineBlocks(1);

            NBitcoin.Block lastBlock = this.node1.GetLastBlock();

            // Blocks progressed
            Assert.NotEqual(currentHash, lastBlock.GetHash());

            // Contract doesn't maintain any balance
            Assert.Equal((ulong)0, this.node1.GetContractBalance(preResponse.NewContractAddress));

            // Receiver contract now has balance
            Assert.Equal((ulong)new Money((int)amount, MoneyUnit.BTC), this.node1.GetContractBalance(receiveResponse.NewContractAddress));

            // Receiver contract stored to state
            Assert.Equal(new byte[] { 1 }, this.node1.GetStorageValue(receiveResponse.NewContractAddress, BasicReceive.ReceiveKey));

            // Log was stored - bloom filter should be non-zero
            Assert.NotEqual(new Bloom(), ((ISmartContractBlockHeader)lastBlock.Header).LogsBloom);

            // Block contains a condensing transaction
            Assert.Equal(3, lastBlock.Transactions.Count);
            Transaction condensingTransaction = lastBlock.Transactions[2];

            Assert.Single(condensingTransaction.Outputs); // Entire balance was forwarded
            byte[] toBytes = condensingTransaction.Outputs[0].ScriptPubKey.ToBytes();
            Assert.Equal((byte)ScOpcodeType.OP_INTERNALCONTRACTTRANSFER, toBytes[0]);
            uint160 toAddress = new uint160(toBytes.Skip(1).ToArray());

            Assert.Equal(receiveResponse.NewContractAddress, toAddress.ToBase58Address(this.node1.CoreNode.FullNode.Network));
            Assert.Equal(new Money((long)amount, MoneyUnit.BTC), condensingTransaction.Outputs[0].Value);

            // Receipt is correct
            ReceiptResponse receipt = this.node1.GetReceipt(response.TransactionId.ToString());

            Assert.Equal(lastBlock.GetHash().ToString(), receipt.BlockHash);
            Assert.Equal(response.TransactionId.ToString(), receipt.TransactionHash);
            Assert.Single(receipt.Logs);
            Assert.Equal(receiveResponse.NewContractAddress, receipt.Logs[0].Address);
            Assert.True(receipt.Success);
            Assert.True(receipt.GasUsed > GasPriceList.BaseCost);
            Assert.Null(receipt.NewContractAddress);
            Assert.Equal(this.node1.MinerAddress.Address, receipt.From);
            Assert.Null(receipt.Error);
            Assert.Equal(preResponse.NewContractAddress, receipt.To);
        }
コード例 #23
0
        private Ticket FindTicket(uint160 contractAddress, Seat seat)
        {
            var tickets = RetrieveTickets(contractAddress);

            return(tickets.FirstOrDefault(ticket => ticket.Seat.Equals(seat)));
        }
コード例 #24
0
        public void InternalTransfer_FromConstructor()
        {
            // Ensure fixture is funded.
            this.mockChain.MineBlocks(1);

            decimal amount = 25;
            Money   senderBalanceBefore = this.node1.WalletSpendableBalance;
            uint256 currentHash         = this.node1.GetLastBlock().GetHash();

            // Deploy contract
            ContractCompilationResult compilationResult = ContractCompiler.CompileFile("SmartContracts/TransferFromConstructor.cs");

            Assert.True(compilationResult.Success);
            uint160 walletUint160 = new uint160(1);
            string  address       = walletUint160.ToBase58Address(this.node1.CoreNode.FullNode.Network);

            string[] parameters = new string[] { string.Format("{0}#{1}", (int)MethodParameterDataType.Address, address) };
            BuildCreateContractTransactionResponse response = this.node1.SendCreateContractTransaction(compilationResult.Compilation, amount, parameters);

            this.mockChain.WaitAllMempoolCount(1);
            this.mockChain.MineBlocks(1);
            Assert.NotNull(this.node1.GetCode(response.NewContractAddress));
            NBitcoin.Block lastBlock = this.node1.GetLastBlock();

            // Blocks progressed
            Assert.NotEqual(currentHash, lastBlock.GetHash());

            // Block contains a condensing transaction
            Assert.Equal(3, lastBlock.Transactions.Count);
            Transaction condensingTransaction = lastBlock.Transactions[2];

            Assert.Equal(2, condensingTransaction.Outputs.Count);

            // 1 output which is contract maintaining its balance
            byte[] toBytes = condensingTransaction.Outputs[0].ScriptPubKey.ToBytes();
            Assert.Equal((byte)ScOpcodeType.OP_INTERNALCONTRACTTRANSFER, toBytes[0]);
            uint160 toAddress = new uint160(toBytes.Skip(1).ToArray());

            Assert.Equal(response.NewContractAddress, toAddress.ToBase58Address(this.node1.CoreNode.FullNode.Network));
            Assert.Equal(new Money((long)amount, MoneyUnit.BTC) / 2, condensingTransaction.Outputs[1].Value);

            // 1 output to address sent in params
            uint160 transferReceiver = this.senderRetriever.GetAddressFromScript(condensingTransaction.Outputs[1].ScriptPubKey).Sender;

            Assert.Equal(walletUint160, transferReceiver);
            Assert.Equal(new Money((long)amount, MoneyUnit.BTC) / 2, condensingTransaction.Outputs[1].Value);

            // Contract maintains half the balance
            Assert.Equal((ulong)new Money((long)amount, MoneyUnit.BTC) / 2, this.node1.GetContractBalance(response.NewContractAddress));

            // Receipt is correct
            ReceiptResponse receipt = this.node1.GetReceipt(response.TransactionId.ToString());

            Assert.Equal(lastBlock.GetHash().ToString(), receipt.BlockHash);
            Assert.Equal(response.TransactionId.ToString(), receipt.TransactionHash);
            Assert.Empty(receipt.Logs); // TODO: Could add logs to this test
            Assert.True(receipt.Success);
            Assert.True(receipt.GasUsed > GasPriceList.BaseCost);
            Assert.Equal(response.NewContractAddress, receipt.NewContractAddress);
            Assert.Equal(this.node1.MinerAddress.Address, receipt.From);
            Assert.Null(receipt.Error);
            Assert.Null(receipt.To);
        }
コード例 #25
0
        private ulong FetchEndOfSale(uint160 contractAddress)
        {
            var serializedValue = _stateRepositoryRoot.GetStorageValue(contractAddress, _serializer.Serialize("EndOfSale"));

            return(_serializer.ToUInt64(serializedValue));
        }
コード例 #26
0
        public void InternalTransfer_BetweenContracts()
        {
            // Ensure fixture is funded.
            this.mockChain.MineBlocks(1);

            // Deploy contract to send to
            ContractCompilationResult receiveCompilationResult = ContractCompiler.CompileFile("SmartContracts/NestedCallsReceiver.cs");

            Assert.True(receiveCompilationResult.Success);
            BuildCreateContractTransactionResponse receiveResponse = this.node1.SendCreateContractTransaction(receiveCompilationResult.Compilation, 0);

            this.mockChain.WaitAllMempoolCount(1);
            this.mockChain.MineBlocks(1);
            Assert.NotNull(this.node1.GetCode(receiveResponse.NewContractAddress));

            // Deploy contract to send from
            ContractCompilationResult compilationResult = ContractCompiler.CompileFile("SmartContracts/NestedCallsStarter.cs");

            Assert.True(compilationResult.Success);
            BuildCreateContractTransactionResponse preResponse = this.node1.SendCreateContractTransaction(compilationResult.Compilation, 0);

            this.mockChain.WaitAllMempoolCount(1);
            this.mockChain.MineBlocks(1);
            Assert.NotNull(this.node1.GetCode(preResponse.NewContractAddress));

            decimal amount = 25;
            Money   senderBalanceBefore = this.node1.WalletSpendableBalance;
            uint256 currentHash         = this.node1.GetLastBlock().GetHash();

            string[] parameters = new string[]
            {
                string.Format("{0}#{1}", (int)MethodParameterDataType.Address, receiveResponse.NewContractAddress)
            };

            BuildCallContractTransactionResponse response = this.node1.SendCallContractTransaction(nameof(NestedCallsStarter.Start), preResponse.NewContractAddress, amount, parameters);

            this.mockChain.WaitAllMempoolCount(1);
            this.mockChain.MineBlocks(1);
            NBitcoin.Block lastBlock = this.node1.GetLastBlock();

            // Blocks progressed
            Assert.NotEqual(currentHash, lastBlock.GetHash());

            // Storage set correctly
            Assert.Equal(BitConverter.GetBytes(NestedCallsStarter.Return), this.node1.GetStorageValue(preResponse.NewContractAddress, NestedCallsStarter.Key));

            // Block contains a condensing transaction
            Assert.Equal(3, lastBlock.Transactions.Count);
            Transaction condensingTransaction = lastBlock.Transactions[2];

            Assert.Equal(2, condensingTransaction.Outputs.Count);

            // 1 output which is starting contract
            byte[] toBytes = condensingTransaction.Outputs[0].ScriptPubKey.ToBytes();
            Assert.Equal((byte)ScOpcodeType.OP_INTERNALCONTRACTTRANSFER, toBytes[0]);
            uint160 toAddress = new uint160(toBytes.Skip(1).ToArray());

            Assert.Equal(preResponse.NewContractAddress, toAddress.ToBase58Address(this.node1.CoreNode.FullNode.Network));

            // Received 1/2 the sent funds + 1/2 of those funds
            Money transferAmount1 = new Money((long)amount, MoneyUnit.BTC) / 2;
            Money transferAmount2 = new Money((long)amount, MoneyUnit.BTC) / 4;

            Assert.Equal(transferAmount1 + transferAmount2, condensingTransaction.Outputs[0].Value);
            Assert.Equal((ulong)(transferAmount1 + transferAmount2), this.node1.GetContractBalance(preResponse.NewContractAddress));

            // 1 output to other deployed contract
            toBytes = condensingTransaction.Outputs[1].ScriptPubKey.ToBytes();
            Assert.Equal((byte)ScOpcodeType.OP_INTERNALCONTRACTTRANSFER, toBytes[0]);
            toAddress = new uint160(toBytes.Skip(1).ToArray());
            Assert.Equal(receiveResponse.NewContractAddress, toAddress.ToBase58Address(this.node1.CoreNode.FullNode.Network));

            // Received 1/2 the sent funds, but sent 1/2 of those funds back
            Assert.Equal(new Money((long)amount, MoneyUnit.BTC) - (transferAmount1 + transferAmount2), condensingTransaction.Outputs[1].Value);
            Assert.Equal((ulong)(new Money((long)amount, MoneyUnit.BTC) - (transferAmount1 + transferAmount2)), this.node1.GetContractBalance(receiveResponse.NewContractAddress));
        }
コード例 #27
0
 /// <summary>
 /// Creates a script to send funds to a given address.
 /// </summary>
 /// <param name="address">The address of the receiver.</param>
 private Script CreateScript(uint160 address)
 {
     return(PayToPubkeyHashTemplate.Instance.GenerateScriptPubKey(new KeyId(address)));
 }
コード例 #28
0
        public void InternalTransfer_ToWalletAddress()
        {
            // Ensure fixture is funded.
            this.mockChain.MineBlocks(1);

            // Deploy contract
            ContractCompilationResult compilationResult = ContractCompiler.CompileFile("SmartContracts/BasicTransfer.cs");

            Assert.True(compilationResult.Success);
            BuildCreateContractTransactionResponse preResponse = this.node1.SendCreateContractTransaction(compilationResult.Compilation, 0);

            this.mockChain.WaitAllMempoolCount(1);
            this.mockChain.MineBlocks(1);
            Assert.NotNull(this.node1.GetCode(preResponse.NewContractAddress));

            decimal amount = 25;
            Money   senderBalanceBefore = this.node1.WalletSpendableBalance;
            uint256 currentHash         = this.node1.GetLastBlock().GetHash();

            // Send amount to contract, which will send to wallet address (address without code)
            uint160 walletUint160 = new uint160(1);
            string  address       = walletUint160.ToBase58Address(this.node1.CoreNode.FullNode.Network);

            string[] parameters = new string[] { string.Format("{0}#{1}", (int)MethodParameterDataType.Address, address) };
            BuildCallContractTransactionResponse response = this.node1.SendCallContractTransaction(
                nameof(BasicTransfer.SendToAddress),
                preResponse.NewContractAddress,
                amount,
                parameters);

            this.mockChain.WaitAllMempoolCount(1);
            this.mockChain.MineBlocks(1);

            NBitcoin.Block lastBlock = this.node1.GetLastBlock();

            // Blocks progressed
            Assert.NotEqual(currentHash, lastBlock.GetHash());

            // Block contains a condensing transaction
            Assert.Equal(3, lastBlock.Transactions.Count);
            Transaction condensingTransaction = lastBlock.Transactions[2];

            Assert.Single(condensingTransaction.Outputs); // Entire balance was forwarded,
            uint160 transferReceiver = this.senderRetriever.GetAddressFromScript(condensingTransaction.Outputs[0].ScriptPubKey).Sender;

            Assert.Equal(walletUint160, transferReceiver);
            Assert.Equal(new Money((long)amount, MoneyUnit.BTC), condensingTransaction.Outputs[0].Value);

            // Contract doesn't maintain any balance
            Assert.Equal((ulong)0, this.node1.GetContractBalance(preResponse.NewContractAddress));

            // Receipt is correct
            ReceiptResponse receipt = this.node1.GetReceipt(response.TransactionId.ToString());

            Assert.Equal(lastBlock.GetHash().ToString(), receipt.BlockHash);
            Assert.Equal(response.TransactionId.ToString(), receipt.TransactionHash);
            Assert.Empty(receipt.Logs); // TODO: Could add logs to this test
            Assert.True(receipt.Success);
            Assert.True(receipt.GasUsed > GasPriceList.BaseCost);
            Assert.Null(receipt.NewContractAddress);
            Assert.Equal(this.node1.MinerAddress.Address, receipt.From);
            Assert.Null(receipt.Error);
            Assert.Equal(preResponse.NewContractAddress, receipt.To);
        }
コード例 #29
0
ファイル: Id.cs プロジェクト: bug-air-drop/NBitcoin.Wicc
 public KeyId(uint160 value)
 {
     _DestBytes = value.ToBytes();
 }
コード例 #30
0
        public void InternalTransfer_Create_WithValueTransfer()
        {
            // Ensure fixture is funded.
            this.mockChain.MineBlocks(1);

            // Deploy contract
            ContractCompilationResult compilationResult = ContractCompiler.CompileFile("SmartContracts/CreationTransfer.cs");

            Assert.True(compilationResult.Success);
            BuildCreateContractTransactionResponse preResponse = this.node1.SendCreateContractTransaction(compilationResult.Compilation, 0);

            this.mockChain.WaitAllMempoolCount(1);
            this.mockChain.MineBlocks(1);
            Assert.NotNull(this.node1.GetCode(preResponse.NewContractAddress));

            decimal amount = 25;
            Money   senderBalanceBefore = this.node1.WalletSpendableBalance;
            uint256 currentHash         = this.node1.GetLastBlock().GetHash();

            // Send amount to contract, which will send to new address of contract it creates
            BuildCallContractTransactionResponse response = this.node1.SendCallContractTransaction(
                nameof(CreationTransfer.CreateAnotherContract),
                preResponse.NewContractAddress,
                amount);

            this.mockChain.WaitAllMempoolCount(1);
            this.mockChain.MineBlocks(1);

            NBitcoin.Block lastBlock = this.node1.GetLastBlock();

            // Blocks progressed
            Assert.NotEqual(currentHash, lastBlock.GetHash());

            // Get created contract address - TODO FIX
            uint160 createdAddress = this.addressGenerator.GenerateAddress(response.TransactionId, 0);

            // Block contains a condensing transaction
            Assert.Equal(3, lastBlock.Transactions.Count);
            Transaction condensingTransaction = lastBlock.Transactions[2];

            Assert.Single(condensingTransaction.Outputs); // Entire balance was forwarded,
            byte[] toBytes = condensingTransaction.Outputs[0].ScriptPubKey.ToBytes();
            Assert.Equal((byte)ScOpcodeType.OP_INTERNALCONTRACTTRANSFER, toBytes[0]);
            uint160 toAddress = new uint160(toBytes.Skip(1).ToArray());

            Assert.Equal(createdAddress, toAddress);
            Assert.Equal(new Money((long)amount, MoneyUnit.BTC), condensingTransaction.Outputs[0].Value);

            // Contract doesn't maintain any balance
            Assert.Equal((ulong)0, this.node1.GetContractBalance(preResponse.NewContractAddress));

            // Created contract received full amount
            Assert.Equal((ulong)new Money((ulong)amount, MoneyUnit.BTC), this.node1.GetContractBalance(createdAddress.ToBase58Address(this.node1.CoreNode.FullNode.Network)));

            // Receipt is correct
            ReceiptResponse receipt = this.node1.GetReceipt(response.TransactionId.ToString());

            Assert.Equal(lastBlock.GetHash().ToString(), receipt.BlockHash);
            Assert.Equal(response.TransactionId.ToString(), receipt.TransactionHash);
            Assert.Empty(receipt.Logs); // TODO: Could add logs to this test
            Assert.True(receipt.Success);
            Assert.True(receipt.GasUsed > GasPriceList.BaseCost);
            Assert.Null(receipt.NewContractAddress);
            Assert.Equal(this.node1.MinerAddress.Address, receipt.From);
            Assert.Null(receipt.Error);
            Assert.Equal(preResponse.NewContractAddress, receipt.To);
        }
コード例 #31
0
 public RawLog(uint160 contractAddress, object log)
 {
     this.ContractAddress = contractAddress;
     this.LogStruct       = log;
 }
コード例 #32
0
        /// <summary>
        /// Sets up a new <see cref="ISmartContractState"/> based on the current state.
        /// </summary>
        public ISmartContractState Create(IState state, RuntimeObserver.IGasMeter gasMeter, uint160 address, BaseMessage message, IStateRepository repository)
        {
            IPersistenceStrategy persistenceStrategy = new MeteredPersistenceStrategy(repository, gasMeter, new BasicKeyEncodingStrategy());

            var persistentState = new PersistentState(persistenceStrategy, this.serializer, address);

            var contractLogger = new MeteredContractLogger(gasMeter, state.LogHolder, this.PrimitiveSerializer);

            var contractState = new SmartContractState(
                state.Block,
                new Message(
                    address.ToAddress(),
                    message.From.ToAddress(),
                    message.Amount
                    ),
                persistentState,
                this.serializer,
                contractLogger,
                this.InternalTransactionExecutorFactory.Create(gasMeter, state),
                new InternalHashHelper(),
                () => state.GetBalance(address));

            return(contractState);
        }
コード例 #33
0
        internal void LogExecutionContext(ILogger logger, IBlock block, IMessage message, uint160 contractAddress)
        {
            var builder = new StringBuilder();

            builder.Append(string.Format("{0}:{1},{2}:{3},", nameof(block.Coinbase), block.Coinbase, nameof(block.Number), block.Number));
            builder.Append(string.Format("{0}:{1},", nameof(contractAddress), contractAddress.ToAddress(this.network)));
            builder.Append(string.Format("{0}:{1},{2}:{3},{4}:{5}", nameof(message.ContractAddress), message.ContractAddress, nameof(message.Sender), message.Sender, nameof(message.Value), message.Value));
            logger.LogTrace("{0}", builder.ToString());
        }
コード例 #34
0
 private Contract(SmartContract instance, Type type, ISmartContractState state, uint160 address)
 {
     this.instance = instance;
     this.State    = state;
     this.Type     = type;
     this.Address  = address;
 }
コード例 #35
0
        /// <summary>
        /// Creates an <see cref="IContract"/> that represents a smart contract in an uninitialized state.
        /// </summary>
        public static IContract CreateUninitialized(Type type, ISmartContractState state, uint160 address)
        {
            var contract = (SmartContract)FormatterServices.GetSafeUninitializedObject(type);

            return(new Contract(contract, type, state, address));
        }
コード例 #36
0
        public void SendAndReceiveSmartContractTransactions()
        {
            using (NodeBuilder builder = NodeBuilder.Create(this))
            {
                CoreNode scSender   = builder.CreateSmartContractNode();
                CoreNode scReceiver = builder.CreateSmartContractNode();

                builder.StartAll();

                scSender.NotInIBD();
                scReceiver.NotInIBD();

                scSender.FullNode.WalletManager().CreateWallet(Password, WalletName);
                scReceiver.FullNode.WalletManager().CreateWallet(Password, WalletName);
                HdAddress addr = scSender.FullNode.WalletManager().GetUnusedAddress(new WalletAccountReference(WalletName, AccountName));
                Features.Wallet.Wallet wallet = scSender.FullNode.WalletManager().GetWalletByName(WalletName);
                Key key = wallet.GetExtendedPrivateKeyForAddress(Password, addr).PrivateKey;

                scSender.SetDummyMinerSecret(new BitcoinSecret(key, scSender.FullNode.Network));
                var maturity = (int)scSender.FullNode.Network.Consensus.CoinbaseMaturity;
                scSender.GenerateStratisWithMiner(maturity + 5);

                // Wait for block repo for block sync to work.
                TestHelper.WaitLoop(() => TestHelper.IsNodeSynced(scSender));

                // The mining should add coins to the wallet.
                var total = scSender.FullNode.WalletManager().GetSpendableTransactionsInWallet(WalletName).Sum(s => s.Transaction.Amount);
                Assert.Equal(Money.COIN * (maturity + 5) * 50, total);

                // Create a token contract
                ulong gasPrice  = 1;
                int   vmVersion = 1;
                Gas   gasLimit  = (Gas)2000;
                SmartContractCompilationResult compilationResult = SmartContractCompiler.CompileFile("SmartContracts/TransferTest.cs");
                Assert.True(compilationResult.Success);

                var contractCarrier = SmartContractCarrier.CreateContract(vmVersion, compilationResult.Compilation, gasPrice, gasLimit);

                var contractCreateScript = new Script(contractCarrier.Serialize());
                var txBuildContext       = new TransactionBuildContext(new WalletAccountReference(WalletName, AccountName), new[] { new Recipient {
                                                                                                                                        Amount = 0, ScriptPubKey = contractCreateScript
                                                                                                                                    } }.ToList(), Password)
                {
                    MinConfirmations = maturity,
                    FeeType          = FeeType.High,
                    DustPrevention   = false
                };

                Transaction transferContractTransaction = scSender.FullNode.WalletTransactionHandler().BuildTransaction(txBuildContext);

                // Broadcast the token transaction to the network
                scSender.FullNode.NodeService <IBroadcasterManager>().BroadcastTransactionAsync(transferContractTransaction);

                // Wait for the token transaction to be picked up by the mempool
                TestHelper.WaitLoop(() => scSender.CreateRPCClient().GetRawMempool().Length > 0);

                // Mine the token transaction and wait for it sync
                scSender.GenerateStratisWithMiner(1);
                TestHelper.WaitLoop(() => TestHelper.IsNodeSynced(scSender));

                // Sync to the receiver node
                scSender.CreateRPCClient().AddNode(scReceiver.Endpoint, true);
                TestHelper.WaitLoop(() => TestHelper.AreNodesSynced(scReceiver, scSender));

                // Ensure that boths nodes has the contract
                ContractStateRepositoryRoot senderState   = scSender.FullNode.NodeService <ContractStateRepositoryRoot>();
                ContractStateRepositoryRoot receiverState = scReceiver.FullNode.NodeService <ContractStateRepositoryRoot>();
                uint160 tokenContractAddress = transferContractTransaction.GetNewContractAddress();
                Assert.NotNull(senderState.GetCode(tokenContractAddress));
                Assert.NotNull(receiverState.GetCode(tokenContractAddress));
                scSender.FullNode.MempoolManager().Clear();

                // Create a transfer token contract
                compilationResult = SmartContractCompiler.CompileFile("SmartContracts/TransferTest.cs");
                Assert.True(compilationResult.Success);
                contractCarrier      = SmartContractCarrier.CreateContract(vmVersion, compilationResult.Compilation, gasPrice, gasLimit);
                contractCreateScript = new Script(contractCarrier.Serialize());
                txBuildContext       = new TransactionBuildContext(new WalletAccountReference(WalletName, AccountName), new[] { new Recipient {
                                                                                                                                    Amount = 0, ScriptPubKey = contractCreateScript
                                                                                                                                } }.ToList(), Password)
                {
                    MinConfirmations = maturity,
                    FeeType          = FeeType.High,
                    DustPrevention   = false
                };

                // Broadcast the token transaction to the network
                transferContractTransaction = scSender.FullNode.WalletTransactionHandler().BuildTransaction(txBuildContext);
                scSender.FullNode.NodeService <IBroadcasterManager>().BroadcastTransactionAsync(transferContractTransaction);

                // Wait for the token transaction to be picked up by the mempool
                TestHelper.WaitLoop(() => scSender.CreateRPCClient().GetRawMempool().Length > 0);
                scSender.GenerateStratisWithMiner(1);

                // Ensure the node is synced
                TestHelper.WaitLoop(() => TestHelper.IsNodeSynced(scSender));

                // Ensure both nodes are synced with each other
                TestHelper.WaitLoop(() => TestHelper.AreNodesSynced(scReceiver, scSender));

                // Ensure that boths nodes has the contract
                senderState          = scSender.FullNode.NodeService <ContractStateRepositoryRoot>();
                receiverState        = scReceiver.FullNode.NodeService <ContractStateRepositoryRoot>();
                tokenContractAddress = transferContractTransaction.GetNewContractAddress();
                Assert.NotNull(senderState.GetCode(tokenContractAddress));
                Assert.NotNull(receiverState.GetCode(tokenContractAddress));
                scSender.FullNode.MempoolManager().Clear();

                // Create a call contract transaction which will transfer funds
                contractCarrier = SmartContractCarrier.CallContract(1, tokenContractAddress, "Test", gasPrice, gasLimit);
                Script contractCallScript = new Script(contractCarrier.Serialize());
                txBuildContext = new TransactionBuildContext(new WalletAccountReference(WalletName, AccountName), new[] { new Recipient {
                                                                                                                              Amount = 1000, ScriptPubKey = contractCallScript
                                                                                                                          } }.ToList(), Password)
                {
                    MinConfirmations = maturity,
                    FeeType          = FeeType.High,
                    DustPrevention   = false
                };

                // Broadcast the token transaction to the network
                transferContractTransaction = scSender.FullNode.WalletTransactionHandler().BuildTransaction(txBuildContext);
                scSender.FullNode.NodeService <IBroadcasterManager>().BroadcastTransactionAsync(transferContractTransaction);
                TestHelper.WaitLoop(() => scSender.CreateRPCClient().GetRawMempool().Length > 0);

                // Mine the transaction
                scSender.GenerateStratisWithMiner(1);

                // Ensure the nodes are synced
                TestHelper.WaitLoop(() => TestHelper.IsNodeSynced(scSender));
                TestHelper.WaitLoop(() => TestHelper.AreNodesSynced(scReceiver, scSender));

                // The balance should now reflect the transfer
                Assert.Equal((ulong)900, senderState.GetCurrentBalance(tokenContractAddress));
            }
        }
コード例 #37
0
 public AssetId(uint160 value)
     : this(value.ToBytes())
 {
 }
コード例 #38
0
ファイル: ContractTxData.cs プロジェクト: georgepinca/src
 /// <summary>
 /// Creates a ContractTxData object for a method invocation
 /// </summary>
 public ContractTxData(int vmVersion, ulong gasPrice, RuntimeObserver.Gas gasLimit, uint160 contractAddress,
                       string method, object[] methodParameters = null)
 {
     this.OpCodeType            = (byte)ScOpcodeType.OP_CALLCONTRACT;
     this.VmVersion             = vmVersion;
     this.GasPrice              = gasPrice;
     this.GasLimit              = gasLimit;
     this.ContractAddress       = contractAddress;
     this.MethodName            = method;
     this.MethodParameters      = methodParameters;
     this.ContractExecutionCode = new byte[0];
 }
コード例 #39
0
ファイル: AssetId.cs プロジェクト: woutersmit/NBitcoin
		public AssetId(uint160 value)
			: this(value.ToBytes())
		{
			_value = value;
		}
コード例 #40
0
ファイル: Uint256Tests.cs プロジェクト: lontivero/BitcoinLite
        public void Addition()
        {
            var half256 = uint256.One << 255;
            uint256 t256 = 0;
            Assert.True(u256_1 + u256_2 == uint256.Parse("0c84685816fb7c5251a71d2203d2899135b1f2584d1de2a41e6a24ea9faf9f54"));
            t256 += u256_1;
            Assert.True(t256 == u256_1);
            t256 += u256_2;
            Assert.True(t256 == u256_1 + u256_2);
            Assert.True(uint256.One + uint256.MaxValue == uint256.Zero);
            Assert.True(uint256.MaxValue + uint256.One == uint256.Zero);
            for (var i = 1; i < 256; ++i)
            {
                Assert.True((uint256.MaxValue >> i) + uint256.One == (half256 >> (i - 1)));
                Assert.True(uint256.One + (uint256.MaxValue >> i) == (half256 >> (i - 1)));
                t256 = (uint256.MaxValue >> i);
                t256 += uint256.One;
                Assert.True(t256 == (half256 >> (i - 1)));
                t256 = (uint256.MaxValue >> i);
                t256 += 1;
                Assert.True(t256 == (half256 >> (i - 1)));
                t256 = (uint256.MaxValue >> i);
                Assert.True(t256++ == (uint256.MaxValue >> i));
                Assert.True(t256 == (half256 >> (i - 1)));
            }
            Assert.True(new uint256(0xbedc77e27940a7UL) + 0xee8d836fce66fbUL == new uint256(0xbedc77e27940a7UL + 0xee8d836fce66fbUL));
            t256 = new uint256(0xbedc77e27940a7UL);
            t256 += 0xee8d836fce66fbUL;
            Assert.True(t256 == new uint256(0xbedc77e27940a7UL + 0xee8d836fce66fbUL));
            t256 -= 0xee8d836fce66fbUL;
            Assert.True(t256 == 0xbedc77e27940a7UL);
            t256 = u256_1;
            Assert.True(++t256 == u256_1 + 1);

            Assert.True(u256_1 - (-u256_2) == u256_1 + u256_2);
            Assert.True(u256_1 - (-uint256.One) == u256_1 + uint256.One);
            Assert.True(u256_1 - uint256.One == u256_1 + (-uint256.One));
            for (int i = 1; i < 256; ++i)
            {
                Assert.True((uint256.MaxValue >> i) - (-uint256.One) == (half256 >> (i - 1)));
                Assert.True((half256 >> (i - 1)) - uint256.One == (uint256.MaxValue >> i));
                t256 = (half256 >> (i - 1));
                Assert.True(t256-- == (half256 >> (i - 1)));
                Assert.True(t256 == (uint256.MaxValue >> i));
                t256 = (half256 >> (i - 1));
                Assert.True(--t256 == (uint256.MaxValue >> i));
            }
            t256 = u256_1;
            Assert.True(--t256 == u256_1 - 1);

            var half160 = uint160.One << 159;
            uint160 t160 = 0;
            Assert.True(u160_1 + u160_2 == uint160.Parse("0c84685816fb7c5251a71d2203d2899135b1f258"));
            t160 += u160_1;
            Assert.True(t160 == u160_1);
            t160 += u160_2;
            Assert.True(t160 == u160_1 + u160_2);
            Assert.True(uint160.One + uint160.MaxValue == uint160.Zero);
            Assert.True(uint160.MaxValue + uint160.One == uint160.Zero);
            for (int i = 1; i < 160; ++i)
            {
                Assert.True((uint160.MaxValue >> i) + uint160.One == (half160 >> (i - 1)));
                Assert.True(uint160.One + (uint160.MaxValue >> i) == (half160 >> (i - 1)));
                t160 = (uint160.MaxValue >> i);
                t160 += uint160.One;
                Assert.True(t160 == (half160 >> (i - 1)));
                t160 = (uint160.MaxValue >> i);
                t160 += 1;
                Assert.True(t160 == (half160 >> (i - 1)));
                t160 = (uint160.MaxValue >> i);
                Assert.True(t160++ == (uint160.MaxValue >> i));
                Assert.True(t160 == (half160 >> (i - 1)));
            }
            Assert.True(new uint160(0xbedc77e27940a7UL) + 0xee8d836fce66fbUL == new uint160(0xbedc77e27940a7UL + 0xee8d836fce66fbUL));
            t160 = new uint160(0xbedc77e27940a7UL);
            t160 += 0xee8d836fce66fbUL;
            Assert.True(t160 == new uint160(0xbedc77e27940a7UL + 0xee8d836fce66fbUL));
            t160 -= 0xee8d836fce66fbUL;
            Assert.True(t160 == 0xbedc77e27940a7UL);
            t160 = u160_1;
            Assert.True(++t160 == u160_1 + 1);

            Assert.True(u160_1 - (-u160_2) == u160_1 + u160_2);
            Assert.True(u160_1 - (-uint160.One) == u160_1 + uint160.One);
            Assert.True(u160_1 - uint160.One == u160_1 + (-uint160.One));
            for (int i = 1; i < 160; ++i)
            {
                Assert.True((uint160.MaxValue >> i) - (-uint160.One) == (half160 >> (i - 1)));
                Assert.True((half160 >> (i - 1)) - uint160.One == (uint160.MaxValue >> i));
                t160 = (half160 >> (i - 1));
                Assert.True(t160-- == (half160 >> (i - 1)));
                Assert.True(t160 == (uint160.MaxValue >> i));
                t160 = (half160 >> (i - 1));
                Assert.True(--t160 == (uint160.MaxValue >> i));
            }
            t160 = u160_1;
            Assert.True(--t160 == u160_1 - 1);
        }