Exemplo n.º 1
0
        public async Task SyncGenesisBlock_False_Rollback()
        {
            var chain = await _mock.CreateChain();

            ChainConfig.Instance.ChainId    = chain.Id.DumpHex();
            NodeConfig.Instance.NodeAccount = Address.Generate().DumpHex();

            var block = GenerateBlock(chain.Id, chain.GenesisBlockHash, GlobalConfig.GenesisBlockHeight + 1);

            var txs = CreateTxs(chain.Id);

            block.Body.Transactions.Add(txs[0].GetHash());
            block.Body.Transactions.Add(txs[2].GetHash());

            block.Body.TransactionList.Add(txs[0]);
            block.Body.TransactionList.Add(txs[2]);
            block.FillTxsMerkleTreeRootInHeader();
            block.Body.BlockHeader = block.Header.GetHash();
            block.Sign(new KeyPairGenerator().Generate());

            var manager       = _mock.MinerClientManager();
            var blockExecutor = _mock.GetBlockExecutor(manager);

            var res = await blockExecutor.ExecuteBlock(block);

            Assert.NotEqual(BlockExecutionResult.Success, res);

            var blockchain = _mock.GetBlockChain(chain.Id);
            var curHash    = await blockchain.GetCurrentBlockHashAsync();

            var index = ((BlockHeader)await blockchain.GetHeaderByHashAsync(curHash)).Index;

            Assert.Equal(GlobalConfig.GenesisBlockHeight, index);
            Assert.Equal(chain.GenesisBlockHash.DumpHex(), curHash.DumpHex());
        }
Exemplo n.º 2
0
        public void Initialize2(Address account, ulong qty)
        {
            var tc = GetInitializeTxnCtxt(SampleContractAddress2, account, qty);

            Executive2.SetTransactionContext(tc).Apply()
            .Wait();
            CommitTrace(tc.Trace).Wait();
        }
Exemplo n.º 3
0
 private Transaction GetETTxn(Address contractAddress, Hash transactionHash)
 {
     return(new Transaction
     {
         From = Address.Zero,
         To = contractAddress,
         MethodName = "GetTransactionEndTime",
         Params = ByteString.CopyFrom(ParamsPacker.Pack(transactionHash))
     });
 }
Exemplo n.º 4
0
 public Transaction GetBalanceTxn(Address contractAddress, Address account)
 {
     return(new Transaction
     {
         From = Address.Zero,
         To = contractAddress,
         MethodName = "GetBalance",
         Params = ByteString.CopyFrom(ParamsPacker.Pack(account))
     });
 }
Exemplo n.º 5
0
 private Transaction GetSleepTxn(Address contractAddress, int milliSeconds)
 {
     return(new Transaction
     {
         From = Address.Zero,
         To = contractAddress,
         IncrementId = NewIncrementId(),
         MethodName = "SleepMilliseconds",
         Params = ByteString.CopyFrom(ParamsPacker.Pack(milliSeconds))
     });
 }
Exemplo n.º 6
0
 private Transaction GetNoActionTxn(Address contractAddress)
 {
     return(new Transaction
     {
         From = Address.Zero,
         To = contractAddress,
         IncrementId = NewIncrementId(),
         MethodName = "NoAction",
         Params = ByteString.Empty
     });
 }
Exemplo n.º 7
0
 private Transaction GetTransferTxn(Address contractAddress, Address from, Address to, ulong qty)
 {
     // TODO: Test with IncrementId
     return(new Transaction
     {
         From = from,
         To = contractAddress,
         IncrementId = NewIncrementId(),
         MethodName = "Transfer",
         Params = ByteString.CopyFrom(ParamsPacker.Pack(from, to, new UInt64Value {
             Value = qty
         }))
     });
 }
Exemplo n.º 8
0
        public ulong GetBalance(Address account)
        {
            var txn     = GetBalanceTxn(account);
            var txnCtxt = new TransactionContext()
            {
                Transaction = txn,
                Trace       = new TransactionTrace()
            };
            var t = SmartContractService.GetExecutiveAsync(SampleContractAddress1, ChainId1);

            t.Wait();
            t.Result.SetTransactionContext(txnCtxt).Apply().Wait();
            return(txnCtxt.Trace.RetVal.Data.DeserializeToUInt64());
        }
Exemplo n.º 9
0
        public ulong GetBalance2(Address account)
        {
            var txn     = GetBalanceTxn(SampleContractAddress2, account);
            var txnRes  = new TransactionResult();
            var txnCtxt = new TransactionContext()
            {
                Transaction = txn
            };

            Executive2.SetDataCache(new Dictionary <DataPath, StateCache>());
            Executive2.SetTransactionContext(txnCtxt).Apply().Wait();

            return(txnCtxt.Trace.RetVal.Data.DeserializeToUInt64());
        }
Exemplo n.º 10
0
        public Transaction GetInitializeTxn(Address account, ulong qty)
        {
            var tx = new Transaction
            {
                From        = Address.Zero,
                To          = SampleContractAddress1,
                IncrementId = NewIncrementId(),
                MethodName  = "Initialize",
                Params      = ByteString.CopyFrom(ParamsPacker.Pack(account, new UInt64Value {
                    Value = qty
                }))
            };

            return(tx);
        }
Exemplo n.º 11
0
        public async Task TwoJobsTest()
        {
            var balances = new List <int>()
            {
                100,
                0
            };
            var addresses = Enumerable.Range(0, balances.Count).Select(x => Address.FromRawBytes(Hash.Generate().ToByteArray())).ToList();

            foreach (var addbal in addresses.Zip(balances, Tuple.Create))
            {
                _mock.Initialize1(addbal.Item1, (ulong)addbal.Item2);
            }

            var txs = new List <Transaction>()
            {
                _mock.GetTransferTxn1(addresses[0], addresses[1], 10),
            };
            var txsHashes = txs.Select(y => y.GetHash()).ToList();

            var finalBalances = new List <int>
            {
                90,
                10
            };

            var service = new ParallelTransactionExecutingService(_mock.ActorEnvironment,
                                                                  new Grouper(_mock.ServicePack.ResourceDetectionService), _mock.ServicePack);

            var traces = await service.ExecuteAsync(txs, _mock.ChainId1, CancellationToken.None);

            foreach (var txTrace in txs.Zip(traces, Tuple.Create))
            {
                Assert.Equal(txTrace.Item1.GetHash(), txTrace.Item2.TransactionId);
                if (!string.IsNullOrEmpty(txTrace.Item2.StdErr))
                {
                    Assert.Null(txTrace.Item2.StdErr);
                }
            }

            foreach (var addFinbal in addresses.Zip(finalBalances, Tuple.Create))
            {
                Assert.Equal((ulong)addFinbal.Item2, _mock.GetBalance1(addFinbal.Item1));
            }
        }
Exemplo n.º 12
0
        private TransactionContext GetInitializeTxnCtxt(Address contractAddress, Address account, ulong qty)
        {
            var tx = new Transaction
            {
                From        = Address.Zero,
                To          = contractAddress,
                IncrementId = NewIncrementId(),
                MethodName  = "Initialize",
                Params      = ByteString.CopyFrom(ParamsPacker.Pack(account, new UInt64Value {
                    Value = qty
                }))
            };

            return(new TransactionContext()
            {
                Transaction = tx
            });
        }
Exemplo n.º 13
0
        public ulong GetBalance1(Address account)
        {
            var txn     = GetBalanceTxn(SampleContractAddress1, account);
            var txnCtxt = new TransactionContext()
            {
                Transaction = txn,
                Trace       = new TransactionTrace()
            };
            // TODO: Check why this doesn't work
//            Executive1.SetDataCache(new Dictionary<DataPath, StateCache>());
//            Executive1.SetTransactionContext(txnCtxt).Apply().Wait();
            var t = SmartContractService.GetExecutiveAsync(SampleContractAddress1, ChainId1);

            t.Wait();
            t.Result.SetTransactionContext(txnCtxt).Apply().Wait();

            return(txnCtxt.Trace.RetVal.Data.DeserializeToUInt64());
        }
Exemplo n.º 14
0
        public async Task Mine()
        {
            var chain = await _mock.CreateChain();

            // create miner
            var keypair     = new KeyPairGenerator().Generate();
            var minerconfig = _mock.GetMinerConfig(chain.Id, 10, keypair.GetAddress().DumpByteArray());

            ChainConfig.Instance.ChainId    = chain.Id.DumpHex();
            NodeConfig.Instance.NodeAccount = keypair.GetAddressHex();
            var txPool = _mock.CreateTxPool();

            txPool.Start();

            var txs = CreateTx(chain.Id);

            foreach (var tx in txs)
            {
                await txPool.AddTransactionAsync(tx);
            }

            var manager = _mock.MinerClientManager();
            var miner   = _mock.GetMiner(minerconfig, txPool, manager);

            GrpcLocalConfig.Instance.ClientToSideChain            = false;
            GrpcLocalConfig.Instance.WaitingIntervalInMillisecond = 10;
            NodeConfig.Instance.ECKeyPair = keypair;
            miner.Init();

            var block = await miner.Mine();

            Assert.NotNull(block);
            Assert.Equal(GlobalConfig.GenesisBlockHeight + 1, block.Header.Index);

            byte[]  uncompressedPrivKey = block.Header.P.ToByteArray();
            Address addr = Address.FromRawBytes(uncompressedPrivKey);

            Assert.Equal(minerconfig.CoinBase, addr);

            ECKeyPair  recipientKeyPair = ECKeyPair.FromPublicKey(uncompressedPrivKey);
            ECVerifier verifier         = new ECVerifier(recipientKeyPair);

            Assert.True(verifier.Verify(block.Header.GetSignature(), block.Header.GetHash().DumpByteArray()));
        }
Exemplo n.º 15
0
 public Transaction GetTransferTxn1(Address from, Address to, ulong qty)
 {
     return(GetTransferTxn(from, to, qty));
 }
Exemplo n.º 16
0
        public async Task ManyJobsTest()
        {
            /*
             *  Job 1: (0-1, 10), (1-2, 9)
             *  Job 2: (3-4, 8)
             *  Job 3: (5-6, 10)
             */

            var balances = new List <ulong>()
            {
                100,
                0,
                0,
                200,
                0,
                300,
                0
            };
            var addresses = Enumerable.Range(0, balances.Count).Select(x => Address.FromRawBytes(Hash.Generate().ToByteArray())).ToList();

            foreach (var addbal in addresses.Zip(balances, Tuple.Create))
            {
                _mock.Initialize1(addbal.Item1, addbal.Item2);
            }

            var txs = new List <Transaction>()
            {
                _mock.GetTransferTxn1(addresses[0], addresses[1], 10),
                _mock.GetTransferTxn1(addresses[1], addresses[2], 9),
                _mock.GetTransferTxn1(addresses[3], addresses[4], 8),
                _mock.GetTransferTxn1(addresses[5], addresses[6], 10),
            };

            var finalBalances = new List <ulong>
            {
                90,
                1,
                9,
                192,
                8,
                290,
                10
            };

            var service = new ParallelTransactionExecutingService(_mock.ActorEnvironment,
                                                                  new Grouper(_mock.ServicePack.ResourceDetectionService), _mock.ServicePack);

            var traces = await service.ExecuteAsync(txs, _mock.ChainId1, CancellationToken.None);

            foreach (var txTrace in txs.Zip(traces, Tuple.Create))
            {
                Assert.Equal(txTrace.Item1.GetHash(), txTrace.Item2.TransactionId);
                if (!string.IsNullOrEmpty(txTrace.Item2.StdErr))
                {
                    Assert.Null(txTrace.Item2.StdErr);
                }
            }

            Assert.Equal(
                string.Join(" ", finalBalances),
                string.Join(" ", addresses.Select(a => _mock.GetBalance1(a)))
                );
        }
Exemplo n.º 17
0
        public void SingleTransactionExecutionTest()
        {
            Address from = Address.FromString(nameof(SingleTransactionExecutionTest) + "/from");
            Address to   = Address.FromString(nameof(SingleTransactionExecutionTest) + "/to");

            _mock.Initialize1(from, 100);
            _mock.Initialize1(to, 0);

            // Normal transfer
            var tx1 = _mock.GetTransferTxn1(from, to, 10);

            _mock.Worker1.Tell(new JobExecutionRequest(0, _mock.ChainId1, new List <Transaction>()
            {
                tx1
            }, TestActor,
                                                       TestActor));

/*
 * Temporarily disabled.
 * TODO: https://github.com/AElfProject/AElf/issues/338
 *          // Start processing
 *          var js1 = ExpectMsg<JobExecutionStatus>();
 *          Assert.Equal(JobExecutionStatus.RequestStatus.Running, js1.Status);
 */
            // Return result
            var trace = ExpectMsg <TransactionTraceMessage>().TransactionTraces.FirstOrDefault();


//            var t = _mock.GetBalanceTxn(_mock.SampleContractAddress1, from);
//            _mock.Worker1.Tell(new JobExecutionRequest(0, _mock.ChainId1, new List<Transaction>(){t}, TestActor, TestActor));
//            var tt = ExpectMsg<TransactionTraceMessage>().TransactionTraces;
//            Assert.Null(tt);


/*
 * Temporarily disabled.
 * TODO: https://github.com/AElfProject/AElf/issues/338
 *          // Completed, two messages will be received
 *          // 1 for sender, 1 for router (in this test both are TestActor)
 *          ExpectMsg<JobExecutionStatus>();
 *          var js2 = ExpectMsg<JobExecutionStatus>();
 *          Assert.Equal(JobExecutionStatus.RequestStatus.Completed, js2.Status);
 */
            Assert.Equal(tx1.GetHash(), trace.TransactionId);
            if (!string.IsNullOrEmpty(trace.StdErr))
            {
                Assert.Null(trace.StdErr);
            }

            Assert.Equal((ulong)90, _mock.GetBalance1(from));
            Assert.Equal((ulong)10, _mock.GetBalance1(to));

/*
 * Temporarily disabled.
 * TODO: https://github.com/AElfProject/AElf/issues/338
 *          // Query status
 *          _mock.Worker1.Tell(new JobExecutionStatusQuery(0));
 *
 *          // Invalid request id as it has already completed
 *          var js3 = ExpectMsg<JobExecutionStatus>();
 *          Assert.Equal(JobExecutionStatus.RequestStatus.InvalidRequestId, js3.Status);
 */
        }
Exemplo n.º 18
0
        public void MultipleTransactionExecutionTest()
        {
            var address1 = Address.FromRawBytes(Hash.Generate().ToByteArray());
            var address2 = Address.FromRawBytes(Hash.Generate().ToByteArray());
            var address3 = Address.FromRawBytes(Hash.Generate().ToByteArray());
            var address4 = Address.FromRawBytes(Hash.Generate().ToByteArray());
            var address5 = Address.FromRawBytes(Hash.Generate().ToByteArray());
            var address6 = Address.FromRawBytes(Hash.Generate().ToByteArray());

            _mock.Initialize1(address1, 100);
            _mock.Initialize1(address2, 0);
            _mock.Initialize1(address3, 200);
            _mock.Initialize1(address4, 0);
            _mock.Initialize1(address5, 300);
            _mock.Initialize1(address6, 0);

            var tx1 = _mock.GetTransferTxn1(address1, address2, 10);
            var tx2 = _mock.GetTransferTxn1(address3, address4, 10);
            var tx3 = _mock.GetTransferTxn1(address5, address6, 10);

            // Normal transfer
            var job1 = new List <Transaction>
            {
                tx1,
                tx2,
                tx3
            };

            _mock.Worker1.Tell(new JobExecutionRequest(0, _mock.ChainId1, job1, TestActor, TestActor));

            // Start processing

/*
 * Temporarily disabled.
 * TODO: https://github.com/AElfProject/AElf/issues/338
 *          var js1 = ExpectMsg<JobExecutionStatus>();
 *          Assert.Equal(JobExecutionStatus.RequestStatus.Running, js1.Status);
 */
            // Return result
            var trace  = ExpectMsg <TransactionTraceMessage>().TransactionTraces;
            var trace1 = trace[0];
            var trace2 = trace[1];
            var trace3 = trace[2];

//            Assert.Null(trace1);
//            _mock.CommitTrace(trace1).Wait();
//            _mock.CommitTrace(trace2).Wait();
//            _mock.CommitTrace(trace3).Wait();
            // Completed

/*
 * Temporarily disabled.
 * TODO: https://github.com/AElfProject/AElf/issues/338
 *          var js2 = ExpectMsg<JobExecutionStatus>();
 *          Assert.Equal(JobExecutionStatus.RequestStatus.Completed, js2.Status);
 */
            Assert.Equal(tx1.GetHash(), trace1.TransactionId);
            Assert.Equal(tx2.GetHash(), trace2.TransactionId);
            Assert.Equal(tx3.GetHash(), trace3.TransactionId);

            if (!string.IsNullOrEmpty(trace1.StdErr))
            {
                Assert.Null(trace1.StdErr);
            }
            Assert.Equal((ulong)90, _mock.GetBalance1(address1));
            Assert.Equal((ulong)10, _mock.GetBalance1(address2));

            if (!string.IsNullOrEmpty(trace2.StdErr))
            {
                Assert.Null(trace2.StdErr);
            }
            Assert.Equal((ulong)190, _mock.GetBalance1(address3));
            Assert.Equal((ulong)10, _mock.GetBalance1(address4));

            if (!string.IsNullOrEmpty(trace3.StdErr))
            {
                Assert.Null(trace3.StdErr);
            }
            Assert.Equal((ulong)290, _mock.GetBalance1(address5));
            Assert.Equal((ulong)10, _mock.GetBalance1(address6));

            // Check sequence
            var end1   = _mock.GetTransactionEndTime1(tx1);
            var start2 = _mock.GetTransactionStartTime1(tx2);

            Assert.True(end1 < start2);
        }
Exemplo n.º 19
0
 public Transaction GetTransferTxn2(Address from, Address to, ulong qty)
 {
     return(GetTransferTxn(SampleContractAddress2, from, to, qty));
 }