示例#1
0
 public SmartContractsController(IBroadcasterManager broadcasterManager,
                                 IBlockStore blockStore,
                                 ConcurrentChain chain,
                                 IConsensusManager consensus,
                                 IDateTimeProvider dateTimeProvider,
                                 ILoggerFactory loggerFactory,
                                 Network network,
                                 IStateRepositoryRoot stateRoot,
                                 IWalletManager walletManager,
                                 IWalletTransactionHandler walletTransactionHandler,
                                 IAddressGenerator addressGenerator,
                                 ISerializer serializer,
                                 IReceiptRepository receiptRepository,
                                 ICallDataSerializer callDataSerializer,
                                 IMethodParameterStringSerializer methodParameterStringSerializer,
                                 ILocalExecutor localExecutor)
 {
     this.stateRoot = stateRoot;
     this.walletTransactionHandler = walletTransactionHandler;
     this.logger             = loggerFactory.CreateLogger(this.GetType().FullName);
     this.network            = network;
     this.coinType           = (CoinType)network.Consensus.CoinType;
     this.chain              = chain;
     this.blockStore         = blockStore;
     this.walletManager      = walletManager;
     this.broadcasterManager = broadcasterManager;
     this.addressGenerator   = addressGenerator;
     this.serializer         = serializer;
     this.receiptRepository  = receiptRepository;
     this.callDataSerializer = callDataSerializer;
     this.methodParameterStringSerializer = methodParameterStringSerializer;
     this.localExecutor = localExecutor;
 }
示例#2
0
 public Account(uint accountIndex, IAddressGenerator addressGenerator, ExtKey externalChain, ExtKey internalChain)
 {
     ExternalChain    = externalChain;
     InternalChain    = internalChain;
     AccountIndex     = accountIndex;
     AddressGenerator = addressGenerator ?? throw new NullReferenceException(nameof(addressGenerator));
 }
示例#3
0
 public SmartContractsController(IBroadcasterManager broadcasterManager,
                                 IBlockStoreCache blockStoreCache,
                                 ConcurrentChain chain,
                                 IDateTimeProvider dateTimeProvider,
                                 ILoggerFactory loggerFactory,
                                 Network network,
                                 IContractStateRoot stateRoot,
                                 IWalletManager walletManager,
                                 IWalletTransactionHandler walletTransactionHandler,
                                 IAddressGenerator addressGenerator,
                                 IContractPrimitiveSerializer contractPrimitiveSerializer,
                                 IReceiptRepository receiptRepository)
 {
     this.stateRoot = stateRoot;
     this.walletTransactionHandler = walletTransactionHandler;
     this.logger                      = loggerFactory.CreateLogger(this.GetType().FullName);
     this.network                     = network;
     this.coinType                    = (CoinType)network.Consensus.CoinType;
     this.chain                       = chain;
     this.blockStoreCache             = blockStoreCache;
     this.walletManager               = walletManager;
     this.broadcasterManager          = broadcasterManager;
     this.addressGenerator            = addressGenerator;
     this.contractPrimitiveSerializer = contractPrimitiveSerializer;
     this.receiptRepository           = receiptRepository;
 }
示例#4
0
 public State(
     IContractPrimitiveSerializer serializer,
     InternalTransactionExecutorFactory internalTransactionExecutorFactory,
     ISmartContractVirtualMachine vm,
     IContractStateRoot repository,
     IBlock block,
     Network network,
     ulong txAmount,
     uint256 transactionHash,
     IAddressGenerator addressGenerator,
     Gas gasLimit)
 {
     this.intermediateState = repository;
     this.LogHolder         = new ContractLogHolder(network);
     this.internalTransfers = new List <TransferInfo>();
     this.BalanceState      = new BalanceState(this.intermediateState, txAmount, this.InternalTransfers);
     this.Network           = network;
     this.Nonce             = 0;
     this.Block             = block;
     this.TransactionHash   = transactionHash;
     this.AddressGenerator  = addressGenerator;
     this.InternalTransactionExecutorFactory = internalTransactionExecutorFactory;
     this.Vm           = vm;
     this.GasRemaining = gasLimit;
     this.Serializer   = serializer;
 }
示例#5
0
        public SmartContractTransactionService(
            Network network,
            IWalletManager walletManager,
            IWalletTransactionHandler walletTransactionHandler,
            IMethodParameterStringSerializer methodParameterStringSerializer,
            ICallDataSerializer callDataSerializer,
            IAddressGenerator addressGenerator,
            IStateRepositoryRoot stateRoot,
            IReserveUtxoService reserveUtxoService,
            IBlockStore blockStore,
            ChainIndexer chainIndexer,
            IContractPrimitiveSerializer primitiveSerializer,
            IContractAssemblyCache contractAssemblyCache,
            IReceiptRepository receiptRepository
            )
        {
            this.network                         = network;
            this.walletManager                   = walletManager;
            this.walletTransactionHandler        = walletTransactionHandler;
            this.methodParameterStringSerializer = methodParameterStringSerializer;
            this.callDataSerializer              = callDataSerializer;
            this.addressGenerator                = addressGenerator;
            this.stateRoot                       = stateRoot;
            this.reserveUtxoService              = reserveUtxoService;

            this.blockStore            = blockStore;
            this.chainIndexer          = chainIndexer;
            this.primitiveSerializer   = primitiveSerializer;
            this.contractAssemblyCache = contractAssemblyCache;
            this.receiptRepository     = receiptRepository;
        }
示例#6
0
        public AccountHDWallet(string accountMasterKey, uint accountIndex, IAddressGenerator addressGenerator)
        {
            BitcoinExtKey bitcoinExtKey = new BitcoinExtKey(accountMasterKey);

            _masterKey        = bitcoinExtKey.ExtKey;
            _accountIndex     = accountIndex;
            _addressGenerator = addressGenerator;
        }
示例#7
0
 protected ContractExecutionFailureTests(T fixture)
 {
     this.mockChain        = fixture.Chain;
     this.node1            = this.mockChain.Nodes[0];
     this.node2            = this.mockChain.Nodes[1];
     this.addressGenerator = new AddressGenerator();
     this.senderRetriever  = new SenderRetriever();
 }
 protected ContractInternalTransferTests(T fixture)
 {
     this.mockChain        = fixture.Chain;
     this.node1            = this.mockChain.Nodes[0];
     this.node2            = this.mockChain.Nodes[1];
     this.addressGenerator = new AddressGenerator();
     this.senderRetriever  = new SenderRetriever();
 }
 /// <inheritdoc />
 public InMemoryDeterministicSeedManager(
     IResourceTracker resourceTracker,
     ISigningHelper signingHelper,
     IAddressGenerator addressGenerator,
     IIotaRepository repository)
     : base(resourceTracker, signingHelper, addressGenerator, repository)
 {
     this.CurrentIndex = -1;
     this.References   = new Dictionary <string, Seed>();
 }
示例#10
0
        public ReceivingAddressPoolTests()
        {
            this.generator = Substitute.For <IAddressGenerator>();
            this.storage   = Substitute.ForPartsOf <FakeReceivingAddressStorage>();
            this.choser    = Substitute.For <IAddressChoser>();

            this.subject = new ReceivingAddressPool(this.generator, this.storage, this.choser);

            MockChoser();
        }
示例#11
0
 public CheckUserInteractor(
     IContactRepository contactRepository,
     IMessenger messenger,
     IAddressGenerator addressGenerator,
     ISignatureFragmentGenerator signatureGenerator)
     : base(signatureGenerator)
 {
     this.ContactRepository = contactRepository;
     this.Messenger         = messenger;
     this.AddressGenerator  = addressGenerator;
 }
示例#12
0
 public CreateUserInteractor(
     IMessenger messenger,
     IAddressGenerator addressGenerator,
     IEncryption encryption,
     ISignatureFragmentGenerator signatureGenerator)
     : base(signatureGenerator)
 {
     this.Messenger        = messenger;
     this.AddressGenerator = addressGenerator;
     this.Encryption       = encryption;
 }
 protected DeterministicSeedManager(
     IResourceTracker resourceTracker,
     ISigningHelper signingHelper,
     IAddressGenerator addressGenerator,
     IIotaRepository repository)
 {
     this.ResourceTracker     = resourceTracker;
     this.SigningHelper       = signingHelper;
     this.AddressGenerator    = addressGenerator;
     this.SubscriptionFactory = new MamChannelSubscriptionFactory(repository, CurlMamParser.Default, CurlMask.Default);
     this.ChannelFactory      = new MamChannelFactory(CurlMamFactory.Default, CurlMerkleTreeFactory.Default, repository);
 }
 public ReflectionVirtualMachine(ISmartContractValidator validator,
                                 InternalTransactionExecutorFactory internalTransactionExecutorFactory,
                                 ILoggerFactory loggerFactory,
                                 Network network,
                                 IAddressGenerator addressGenerator)
 {
     this.validator = validator;
     this.internalTransactionExecutorFactory = internalTransactionExecutorFactory;
     this.logger           = loggerFactory.CreateLogger(this.GetType());
     this.network          = network;
     this.addressGenerator = addressGenerator;
 }
示例#15
0
        /// <inheritdoc />
        public CachedIotaRestRepository(
            IIotaClient client,
            IPoWService powService,
            IAddressGenerator addressGenerator       = null,
            IDbConnectionSupplier connectionSupplier = null,
            string databaseFilename = "iotacache.sqlite")
            : base(client, powService, addressGenerator)
        {
            this.ConnectionSupplier = connectionSupplier ?? new DefaultDbConnectionSupplier();
            this.ConnectionString   = $"Data Source={databaseFilename};Version=3;";

            DatabaseInitializer.InitCache(this.ConnectionSupplier, databaseFilename);
        }
示例#16
0
        public HdWalletBase(string words, string seedPassword, IAddressGenerator addressGenerator)
        {
            if (string.IsNullOrEmpty(words))
            {
                throw new NullReferenceException(nameof(words));
            }

            var mneumonic = new Mnemonic(words);

            BIP39Seed = mneumonic.DeriveSeed(seedPassword).ToHex();

            this.AddressGenerator = addressGenerator;
        }
示例#17
0
        /// <inheritdoc />
        public SeedManager(
            IResourceTracker resourceTracker,
            ISigningHelper signingHelper,
            IAddressGenerator addressGenerator,
            IIotaRepository repository,
            IEncryption encryption,
            string databaseFilename = "iotafhir.sqlite")
            : base(resourceTracker, signingHelper, addressGenerator, repository)
        {
            this.Encryption       = encryption;
            this.ConnectionString = databaseFilename;

            this.Init(databaseFilename);
        }
示例#18
0
 public StateFactory(
     Network network,
     IContractPrimitiveSerializer contractPrimitiveSerializer,
     ISmartContractVirtualMachine vm,
     IAddressGenerator addressGenerator,
     InternalTransactionExecutorFactory internalTransactionExecutorFactory
     )
 {
     this.network = network;
     this.contractPrimitiveSerializer = contractPrimitiveSerializer;
     this.vm = vm;
     this.addressGenerator = addressGenerator;
     this.internalTransactionExecutorFactory = internalTransactionExecutorFactory;
 }
示例#19
0
 public SmartContractTransactionService(
     Network network,
     IWalletManager walletManager,
     IWalletTransactionHandler walletTransactionHandler,
     IMethodParameterStringSerializer methodParameterStringSerializer,
     ICallDataSerializer callDataSerializer,
     IAddressGenerator addressGenerator)
 {
     this.network                         = network;
     this.walletManager                   = walletManager;
     this.walletTransactionHandler        = walletTransactionHandler;
     this.methodParameterStringSerializer = methodParameterStringSerializer;
     this.callDataSerializer              = callDataSerializer;
     this.addressGenerator                = addressGenerator;
 }
        /// <inheritdoc />
        public SqlLiteDeterministicSeedManager(
            IResourceTracker resourceTracker,
            ISigningHelper signingHelper,
            IAddressGenerator addressGenerator,
            IIotaRepository repository,
            IEncryption encryption,
            IDbConnectionSupplier connectionSupplier = null,
            string databaseFilename = "iotafhir.sqlite")
            : base(resourceTracker, signingHelper, addressGenerator, repository)
        {
            this.Encryption         = encryption;
            this.ConnectionSupplier = connectionSupplier ?? new DefaultDbConnectionSupplier();
            this.ConnectionString   = $"Data Source={databaseFilename};Version=3;";

            DatabaseInitializer.InitFhirDatabase(this.ConnectionSupplier, databaseFilename);
        }
 public ReflectionVirtualMachine(ISmartContractValidator validator,
                                 InternalTransactionExecutorFactory internalTransactionExecutorFactory,
                                 ILoggerFactory loggerFactory,
                                 Network network,
                                 IAddressGenerator addressGenerator,
                                 ILoader assemblyLoader,
                                 IContractModuleDefinitionReader moduleDefinitionReader,
                                 IContractPrimitiveSerializer contractPrimitiveSerializer)
 {
     this.validator = validator;
     this.internalTransactionExecutorFactory = internalTransactionExecutorFactory;
     this.logger                      = loggerFactory.CreateLogger(this.GetType());
     this.network                     = network;
     this.addressGenerator            = addressGenerator;
     this.assemblyLoader              = assemblyLoader;
     this.moduleDefinitionReader      = moduleDefinitionReader;
     this.contractPrimitiveSerializer = contractPrimitiveSerializer;
 }
 public SmartContractTransactionService(
     Network network,
     IWalletManager walletManager,
     IWalletTransactionHandler walletTransactionHandler,
     IMethodParameterStringSerializer methodParameterStringSerializer,
     ICallDataSerializer callDataSerializer,
     IAddressGenerator addressGenerator,
     IStateRepositoryRoot stateRoot,
     IReserveUtxoService reserveUtxoService
     )
 {
     this.network                         = network;
     this.walletManager                   = walletManager;
     this.walletTransactionHandler        = walletTransactionHandler;
     this.methodParameterStringSerializer = methodParameterStringSerializer;
     this.callDataSerializer              = callDataSerializer;
     this.addressGenerator                = addressGenerator;
     this.stateRoot                       = stateRoot;
     this.reserveUtxoService              = reserveUtxoService;
 }
 public SmartContractsController(IBroadcasterManager broadcasterManager,
                                 IConsensusLoop consensus,
                                 IDateTimeProvider dateTimeProvider,
                                 ILoggerFactory loggerFactory,
                                 Network network,
                                 ISmartContractReceiptStorage receiptStorage,
                                 ContractStateRepositoryRoot stateRoot,
                                 IWalletManager walletManager,
                                 IWalletTransactionHandler walletTransactionHandler,
                                 IAddressGenerator addressGenerator)
 {
     this.receiptStorage           = receiptStorage;
     this.stateRoot                = stateRoot;
     this.walletTransactionHandler = walletTransactionHandler;
     this.logger             = loggerFactory.CreateLogger(this.GetType().FullName);
     this.network            = network;
     this.coinType           = (CoinType)network.Consensus.CoinType;
     this.walletManager      = walletManager;
     this.broadcasterManager = broadcasterManager;
     this.addressGenerator   = addressGenerator;
 }
示例#24
0
        public ReceivingAddressPool(
            IAddressGenerator generator,
            IReceivingAddressStorage storage,
            IAddressChoser choser)
        {
            if (generator == null)
            {
                throw new ArgumentNullException(nameof(generator));
            }

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

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

            this.generator = generator;
            this.storage   = storage;
            this.choser    = choser;
        }
示例#25
0
        public ReceivingAddressPool(
            IAddressGenerator generator,
            IReceivingAddressRepository repository,
            IAddressChoser choser)
        {
            if (generator == null)
            {
                throw new ArgumentNullException(nameof(generator));
            }

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

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

            this.generator  = generator;
            this.repository = repository;
            this.choser     = choser;
        }
示例#26
0
 public uint160 GenerateAddress(IAddressGenerator addressGenerator)
 {
     return(addressGenerator.GenerateAddress(this.TransactionHash, this.NonceGenerator.Next));
 }
示例#27
0
        public void SendAndReceiveSmartContractTransactions()
        {
            NetworkRegistration.Register(new SmartContractsRegTest());

            using (SmartContractNodeBuilder builder = SmartContractNodeBuilder.Create(this))
            {
                CoreNode scSender   = builder.CreateSmartContractPowNode().WithWallet().Start();
                CoreNode scReceiver = builder.CreateSmartContractPowNode().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.
                int spendableBlocks = GetSpendableBlocks(maturity + 5, maturity);
                var total           = scSender.FullNode.WalletManager().GetSpendableTransactionsInWallet(WalletName).Sum(s => s.Transaction.Amount);
                Assert.Equal(Money.COIN * spendableBlocks * 50, total);

                // Create a token contract.
                ulong gasPrice  = SmartContractMempoolValidator.MinGasPrice;
                int   vmVersion = 1;
                Gas   gasLimit  = (Gas)(SmartContractFormatRule.GasLimitMaximum / 2);
                ContractCompilationResult compilationResult = ContractCompiler.CompileFile("SmartContracts/TransferTest.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),
                    MinConfirmations = maturity,
                    TransactionFee   = new Money(1, MoneyUnit.BTC),
                    FeeType          = FeeType.High,
                    WalletPassword   = Password,
                    Recipients       = new[] { new Recipient {
                                                   Amount = 0, ScriptPubKey = contractCreateScript
                                               } }.ToList()
                };

                Transaction transferContractTransaction = (scSender.FullNode.NodeService <IWalletTransactionHandler>() as SmartContractWalletTransactionHandler).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 to sync.
                TestHelper.MineBlocks(scSender, 1);

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

                // Ensure that both nodes have 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/TransferTest.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),
                    MinConfirmations = maturity,
                    TransactionFee   = new Money(1, MoneyUnit.BTC),
                    FeeType          = FeeType.High,
                    WalletPassword   = Password,
                    Recipients       = new[] { new Recipient {
                                                   Amount = 0, ScriptPubKey = contractCreateScript
                                               } }.ToList()
                };

                // Broadcast the token transaction to the network.
                transferContractTransaction = (scSender.FullNode.NodeService <IWalletTransactionHandler>() as SmartContractWalletTransactionHandler).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);
                TestHelper.MineBlocks(scSender, 1);

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

                // Ensure that both nodes have the contract.
                senderState          = scSender.FullNode.NodeService <IStateRepositoryRoot>();
                receiverState        = scReceiver.FullNode.NodeService <IStateRepositoryRoot>();
                tokenContractAddress = addressGenerator.GenerateAddress(transferContractTransaction.GetHash(), 0);
                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),
                    MinConfirmations = maturity,
                    TransactionFee   = new Money(1, MoneyUnit.BTC),
                    FeeType          = FeeType.High,
                    WalletPassword   = Password,
                    Recipients       = new[] { new Recipient {
                                                   Amount = 1000, ScriptPubKey = contractCallScript
                                               } }.ToList()
                };

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

                // Mine the transaction.
                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));
            }
        }
示例#28
0
        public void SendAndReceiveSmartContractTransactionsOnPosNetwork()
        {
            using (NodeBuilder builder = NodeBuilder.Create(this))
            {
                CoreNode scSender   = builder.CreateSmartContractPosNode();
                CoreNode scReceiver = builder.CreateSmartContractPosNode();

                builder.StartAll();

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

                scSender.FullNode.WalletManager().CreateWallet(Password, WalletName, Passphrase);
                scReceiver.FullNode.WalletManager().CreateWallet(Password, WalletName, Passphrase);

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

                // 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 * 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 contractCarrier = ContractCarrier.CreateContract(vmVersion, compilationResult.Compilation, gasPrice, gasLimit);

                var contractCreateScript = new Script(contractCarrier.Serialize());
                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
                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
                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);
                contractCarrier      = ContractCarrier.CreateContract(vmVersion, compilationResult.Compilation, gasPrice, gasLimit);
                contractCreateScript = new Script(contractCarrier.Serialize());
                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);
                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));

                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
                contractCarrier = ContractCarrier.CallContract(1, tokenContractAddress, "Test", gasPrice, gasLimit);
                Script contractCallScript = new Script(contractCarrier.Serialize());
                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);
                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));
            }
        }
示例#29
0
        public void SendAndReceiveSmartContractTransactions()
        {
            using (NodeBuilder builder = NodeBuilder.Create(this))
            {
                CoreNode scSender   = builder.CreateSmartContractPowNode();
                CoreNode scReceiver = builder.CreateSmartContractPowNode();

                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(scSender.FullNode.Network)
                {
                    AccountReference = new WalletAccountReference(WalletName, AccountName),
                    MinConfirmations = maturity,
                    FeeType          = FeeType.High,
                    WalletPassword   = Password,
                    Recipients       = new[] { new Recipient {
                                                   Amount = 0, ScriptPubKey = contractCreateScript
                                               } }.ToList()
                };

                Transaction transferContractTransaction = (scSender.FullNode.NodeService <IWalletTransactionHandler>() as SmartContractWalletTransactionHandler).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>();
                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 = 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(scSender.FullNode.Network)
                {
                    AccountReference = new WalletAccountReference(WalletName, AccountName),
                    MinConfirmations = maturity,
                    FeeType          = FeeType.High,
                    WalletPassword   = Password,
                    Recipients       = new[] { new Recipient {
                                                   Amount = 0, ScriptPubKey = contractCreateScript
                                               } }.ToList()
                };

                // Broadcast the token transaction to the network
                transferContractTransaction = (scSender.FullNode.NodeService <IWalletTransactionHandler>() as SmartContractWalletTransactionHandler).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 = addressGenerator.GenerateAddress(transferContractTransaction.GetHash(), 0);
                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(scSender.FullNode.Network)
                {
                    AccountReference = new WalletAccountReference(WalletName, AccountName),
                    MinConfirmations = maturity,
                    FeeType          = FeeType.High,
                    WalletPassword   = Password,
                    Recipients       = new[] { new Recipient {
                                                   Amount = 1000, ScriptPubKey = contractCallScript
                                               } }.ToList()
                };

                // Broadcast the token transaction to the network
                transferContractTransaction = (scSender.FullNode.NodeService <IWalletTransactionHandler>() as SmartContractWalletTransactionHandler).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));
            }
        }
 public ContractCreationTests()
 {
     this.network          = new SmartContractsRegTest();
     this.addressGenerator = new AddressGenerator();
 }