public void Test() { _contract.GetContractOwner(AddressHelpers.GetSystemContractAddress(_mock.ChainId1, SmartContractType.BasicContractZero.ToString())); Assert.True(_contract.TransactionContext.Trace.StdErr.IsNullOrEmpty()); var owner = _contract.TransactionContext.Trace.RetVal.Data.DeserializeToPbMessage <Address>(); Assert.Equal(_contract.Sender, owner); // Initialize _contract.Initialize("ELF", "AElf Token", 1000000000, 2); Assert.True(string.IsNullOrEmpty(_contract.TransactionContext.Trace.StdErr)); Assert.True(_contract.TransactionContext.Trace.IsSuccessful()); // Basic info query Assert.Equal("ELF", _contract.Symbol()); Assert.Equal("AElf Token", _contract.TokenName()); Assert.Equal((ulong)1000000000, _contract.TotalSupply()); Assert.Equal((uint)2, _contract.Decimals()); // Cannot Initialize more than one time try { _contract.Initialize("ELF", "AElf Token", 1000000000, 2); } catch (Exception e) { Assert.Equal(ExecutionStatus.ContractError, _contract.TransactionContext.Trace.ExecutionStatus); } }
public async Task DeployUserContract() { var reg = new SmartContractRegistration { Category = 0, ContractBytes = ByteString.CopyFrom(SmartContractZeroCode), ContractHash = Hash.Zero }; var chain = await _chainCreationService.CreateNewChainAsync(ChainId, new List <SmartContractRegistration> { reg }); var code = ExampleContractCode; var contractAddressZero = AddressHelpers.GetSystemContractAddress(ChainId, GlobalConfig.GenesisBasicContract); var txnDep = new Transaction() { From = Address.Zero, To = contractAddressZero, IncrementId = NewIncrementId(), MethodName = "DeploySmartContract", Params = ByteString.CopyFrom(ParamsPacker.Pack(0, code)) }; var txnCtxt = new TransactionContext { Transaction = txnDep }; var executive = await _smartContractService.GetExecutiveAsync(contractAddressZero, ChainId); await executive.SetTransactionContext(txnCtxt).Apply(); await txnCtxt.Trace.CommitChangesAsync(_stateStore); Assert.True(string.IsNullOrEmpty(txnCtxt.Trace.StdErr)); var address = Address.FromRawBytes(txnCtxt.Trace.RetVal.Data.DeserializeToBytes()); var regExample = new SmartContractRegistration { Category = 0, ContractBytes = ByteString.CopyFrom(code), ContractHash = Hash.FromRawBytes(code) }; var copy = await _smartContractManager.GetAsync(address); Assert.Equal(regExample, copy); }
public async Task SideChainLifetime() { Init(); _contract = new SideChainContractShim(Mock, AddressHelpers.GetSystemContractAddress(Mock.ChainId1, SmartContractType.SideChainContract.ToString())); // var chainId = Hash.Generate(); var chainId = Hash.FromString("Chain1"); var lockedAddress = Address.FromRawBytes(Hash.FromString("LockedAddress1").ToByteArray()); ulong lockedToken = 10000; // create new chain var bytes = await _contract.CreateSideChain(chainId, lockedAddress, lockedToken); Assert.Equal(chainId.DumpByteArray(), bytes); // check status var status = await _contract.GetChainStatus(chainId); Assert.Equal(1, status); var sn = await _contract.GetCurrentSideChainSerialNumber(); Assert.Equal(1, (int)sn); var tokenAmount = await _contract.GetLockedToken(chainId); Assert.Equal(lockedToken, tokenAmount); var address = await _contract.GetLockedAddress(chainId); Assert.Equal(lockedAddress.DumpByteArray(), address); // authorize the chain await _contract.ApproveSideChain(chainId); Assert.True(_contract.TransactionContext.Trace.IsSuccessful()); status = await _contract.GetChainStatus(chainId); Assert.Equal(2, status); // dispose await _contract.DisposeSideChain(chainId); Assert.True(_contract.TransactionContext.Trace.IsSuccessful()); status = await _contract.GetChainStatus(chainId); Assert.Equal(3, status); }
public List <Transaction> CreateTx(Hash chainId) { var contractAddressZero = AddressHelpers.GetSystemContractAddress(chainId, GlobalConfig.GenesisBasicContract); Console.WriteLine($"zero {contractAddressZero}"); var code = ExampleContractCode; ECKeyPair keyPair = new KeyPairGenerator().Generate(); ECSigner signer = new ECSigner(); var txPrint = new Transaction() { From = keyPair.GetAddress(), To = contractAddressZero, IncrementId = NewIncrementId(), MethodName = "Print", Params = ByteString.CopyFrom(new Parameters() { Params = { new Param { StrVal = "AElf" } } }.ToByteArray()), Fee = TxPoolConfig.Default.FeeThreshold + 1 }; Hash hash = txPrint.GetHash(); ECSignature signature = signer.Sign(keyPair, hash.DumpByteArray()); txPrint.Sig = new Signature { P = ByteString.CopyFrom(keyPair.PublicKey.Q.GetEncoded()), R = ByteString.CopyFrom(signature.R), S = ByteString.CopyFrom(signature.S), }; var txs = new List <Transaction>() { txPrint }; return(txs); }
public List <Transaction> CreateTx(Hash chainId) { var contractAddressZero = AddressHelpers.GetSystemContractAddress(chainId, GlobalConfig.GenesisBasicContract); var keyPair = new KeyPairGenerator().Generate(); var signer = new ECSigner(); var txPrint = new Transaction() { From = keyPair.GetAddress(), To = contractAddressZero, MethodName = "Print", Params = ByteString.CopyFrom(new Parameters() { Params = { new Param { StrVal = "AElf" } } }.ToByteArray()), Fee = 0 }; var hash = txPrint.GetHash(); var signature = signer.Sign(keyPair, hash.DumpByteArray()); txPrint.Sig = new Signature { P = ByteString.CopyFrom(keyPair.PublicKey.Q.GetEncoded()), R = ByteString.CopyFrom(signature.R), S = ByteString.CopyFrom(signature.S) }; var txs = new List <Transaction> { txPrint }; return(txs); }
/// <summary> /// Generate a system tx for parent chain block info and broadcast it. /// </summary> /// <returns></returns> private async Task GenerateTransactionWithParentChainBlockInfo() { var parentChainBlockInfo = GetParentChainBlockInfo(); if (parentChainBlockInfo == null) { return; } try { var bn = await _blockChain.GetCurrentBlockHeightAsync(); bn = bn > 4 ? bn - 4 : 0; var bh = bn == 0 ? Hash.Genesis : (await _blockChain.GetHeaderByHeightAsync(bn)).GetHash(); var bhPref = bh.Value.Where((x, i) => i < 4).ToArray(); var tx = new Transaction { From = _keyPair.GetAddress(), To = AddressHelpers.GetSystemContractAddress(Config.ChainId, SmartContractType.SideChainContract.ToString()), RefBlockNumber = bn, RefBlockPrefix = ByteString.CopyFrom(bhPref), MethodName = "WriteParentChainBlockInfo", Sig = new Signature { P = ByteString.CopyFrom(_keyPair.GetEncodedPublicKey()) }, Type = TransactionType.CrossChainBlockInfoTransaction, Params = ByteString.CopyFrom(ParamsPacker.Pack(parentChainBlockInfo)), Time = Timestamp.FromDateTime(DateTime.UtcNow) }; // sign tx var signature = new ECSigner().Sign(_keyPair, tx.GetHash().DumpByteArray()); tx.Sig.R = ByteString.CopyFrom(signature.R); tx.Sig.S = ByteString.CopyFrom(signature.S); await InsertTransactionToPool(tx); _logger?.Trace($"Generated Cross chain info transaction {tx.GetHash()}"); } catch (Exception e) { _logger?.Error(e, "PCB transaction generation failed."); } }
public async Task SmartContractZeroByCreation() { var reg = new SmartContractRegistration { Category = 0, ContractBytes = ByteString.CopyFrom(SmartContractZeroCode), ContractHash = Hash.Zero }; var chain = await _chainCreationService.CreateNewChainAsync(ChainId, new List <SmartContractRegistration> { reg }); var contractAddressZero = AddressHelpers.GetSystemContractAddress(ChainId, GlobalConfig.GenesisBasicContract); var copy = await _smartContractManager.GetAsync(contractAddressZero); // throw exception if not registered Assert.Equal(reg, copy); }
public async Task MerklePathTest() { Init(); var chainId = Mock.ChainId1; _contract = new SideChainContractShim(Mock, AddressHelpers.GetSystemContractAddress(chainId, SmartContractType.SideChainContract.ToString())); ulong pHeight = 1; ParentChainBlockRootInfo parentChainBlockRootInfo = new ParentChainBlockRootInfo { ChainId = chainId, Height = pHeight, SideChainTransactionsRoot = Hash.Generate(), SideChainBlockHeadersRoot = Hash.Generate() }; ParentChainBlockInfo parentChainBlockInfo = new ParentChainBlockInfo { Root = parentChainBlockRootInfo }; parentChainBlockInfo.IndexedBlockInfo.Add(0, new MerklePath { Path = { Hash.FromString("Block1"), Hash.FromString("Block2"), Hash.FromString("Block3") } }); await _contract.WriteParentChainBLockInfo(parentChainBlockInfo); ChainConfig.Instance.ChainId = chainId.DumpHex(); var crossChainInfo = new CrossChainInfo(Mock.StateStore); var merklepath = crossChainInfo.GetTxRootMerklePathInParentChain(0); Assert.NotNull(merklepath); Assert.Equal(parentChainBlockInfo.IndexedBlockInfo[0], merklepath); var parentHeight = crossChainInfo.GetParentChainCurrentHeight(); Assert.Equal(pHeight, parentHeight); var boundHeight = crossChainInfo.GetBoundParentChainHeight(0); Assert.Equal(parentChainBlockRootInfo.Height, boundHeight); var boundBlockInfo = crossChainInfo.GetBoundParentChainBlockInfo(parentChainBlockRootInfo.Height); Assert.Equal(parentChainBlockInfo, boundBlockInfo); }
public Address GenesisContractHash(Hash chainId, SmartContractType contractType) { return(AddressHelpers.GetSystemContractAddress(chainId, contractType.ToString())); }
public async Task Invoke() { var reg = new SmartContractRegistration { Category = 0, ContractBytes = ByteString.CopyFrom(SmartContractZeroCode), ContractHash = Hash.Zero, Type = (int)SmartContractType.BasicContractZero }; var chain = await _chainCreationService.CreateNewChainAsync(ChainId, new List <SmartContractRegistration> { reg }); var code = ExampleContractCode; var contractAddressZero = AddressHelpers.GetSystemContractAddress(ChainId, GlobalConfig.GenesisBasicContract); var txnDep = new Transaction() { From = Address.Zero, To = contractAddressZero, IncrementId = NewIncrementId(), MethodName = "DeploySmartContract", Params = ByteString.CopyFrom(ParamsPacker.Pack(1, code)) }; var txnCtxt = new TransactionContext() { Transaction = txnDep }; var executive = await _smartContractService.GetExecutiveAsync(contractAddressZero, ChainId); await executive.SetTransactionContext(txnCtxt).Apply(); await txnCtxt.Trace.CommitChangesAsync(_stateStore); var bs = txnCtxt.Trace.RetVal; var address = Address.FromRawBytes(bs.Data.DeserializeToBytes()); #region initialize account balance var account = Address.FromRawBytes(Hash.Generate().ToByteArray()); var txnInit = new Transaction { From = Address.Zero, To = address, IncrementId = NewIncrementId(), MethodName = "Initialize", Params = ByteString.CopyFrom(ParamsPacker.Pack(account, new UInt64Value { Value = 101 })) }; var txnInitCtxt = new TransactionContext() { Transaction = txnInit }; var executiveUser = await _smartContractService.GetExecutiveAsync(address, ChainId); await executiveUser.SetTransactionContext(txnInitCtxt).Apply(); await txnInitCtxt.Trace.CommitChangesAsync(_stateStore); #endregion initialize account balance #region check account balance var txnBal = new Transaction { From = Address.Zero, To = address, IncrementId = NewIncrementId(), MethodName = "GetBalance", Params = ByteString.CopyFrom(ParamsPacker.Pack(account)) }; var txnBalCtxt = new TransactionContext() { Transaction = txnBal }; await executiveUser.SetTransactionContext(txnBalCtxt).Apply(); Assert.Equal((ulong)101, txnBalCtxt.Trace.RetVal.Data.DeserializeToUInt64()); #endregion #region check account balance var txnPrint = new Transaction { From = Address.Zero, To = address, IncrementId = NewIncrementId(), MethodName = "Print" }; var txnPrintcxt = new TransactionContext() { Transaction = txnBal }; await executiveUser.SetTransactionContext(txnPrintcxt).Apply(); await txnPrintcxt.Trace.CommitChangesAsync(_stateStore); //Assert.Equal((ulong)101, txnBalCtxt.Trace.RetVal.DeserializeToUInt64()); #endregion }
public async Task VerifyTransactionTest() { Init(); var chainId = Mock.ChainId1; ChainConfig.Instance.ChainId = chainId.DumpHex(); _contract = new SideChainContractShim(Mock, AddressHelpers.GetSystemContractAddress(chainId, SmartContractType.SideChainContract.ToString())); ulong pHeight = 1; ParentChainBlockRootInfo pcbr1 = new ParentChainBlockRootInfo { ChainId = chainId, Height = pHeight, SideChainTransactionsRoot = Hash.Generate(), SideChainBlockHeadersRoot = Hash.Generate() }; ParentChainBlockInfo pcb1 = new ParentChainBlockInfo { Root = pcbr1 }; pcb1.IndexedBlockInfo.Add(0, new MerklePath { Path = { Hash.FromString("Block1"), Hash.FromString("Block2"), Hash.FromString("Block3") } }); await _contract.WriteParentChainBLockInfo(pcb1); var crossChainInfo = new CrossChainInfo(Mock.StateStore); var parentHeight = crossChainInfo.GetParentChainCurrentHeight(); Assert.Equal(pHeight, parentHeight); Transaction t1 = new Transaction { From = Address.FromString("1"), To = Address.FromString("2"), MethodName = "test", Sig = new Signature { P = ByteString.Empty, R = ByteString.Empty, }, Params = ByteString.Empty, RefBlockNumber = 0, RefBlockPrefix = ByteString.Empty }; var hashCount = 10; var list1 = new List <Hash> { t1.GetHash() }; for (int i = 0; i < hashCount; i++) { list1.Add(Hash.Generate()); } var bmt1 = new BinaryMerkleTree(); bmt1.AddNodes(list1); var root1 = bmt1.ComputeRootHash(); var sc1BlockInfo = new SideChainBlockInfo { Height = pHeight, BlockHeaderHash = Hash.Generate(), ChainId = Hash.Generate(), TransactionMKRoot = root1 }; Transaction t2 = new Transaction { From = Address.FromString("3"), To = Address.FromString("4"), MethodName = "test", Sig = new Signature { P = ByteString.Empty, R = ByteString.Empty, }, Params = ByteString.Empty, RefBlockNumber = 1, RefBlockPrefix = ByteString.Empty }; var list2 = new List <Hash> { t2.GetHash(), Hash.FromString("d"), Hash.FromString("e"), Hash.FromString("f"), Hash.FromString("a"), Hash.FromString("b"), Hash.FromString("c") }; var bmt2 = new BinaryMerkleTree(); bmt2.AddNodes(list2); var root2 = bmt2.ComputeRootHash(); var sc2BlockInfo = new SideChainBlockInfo { Height = pHeight, BlockHeaderHash = Hash.Generate(), ChainId = Hash.Generate(), TransactionMKRoot = root2 }; var block = new Block { Header = new BlockHeader(), Body = new BlockBody() }; block.Body.IndexedInfo.Add(new List <SideChainBlockInfo> { sc1BlockInfo, sc2BlockInfo }); block.Body.CalculateMerkleTreeRoots(); pHeight = 2; ParentChainBlockRootInfo parentChainBlockRootInfo = new ParentChainBlockRootInfo { ChainId = chainId, Height = pHeight, SideChainTransactionsRoot = block.Body.SideChainTransactionsRoot, SideChainBlockHeadersRoot = Hash.FromString("SideChainBlockHeadersRoot") }; ParentChainBlockInfo parentChainBlockInfo = new ParentChainBlockInfo { Root = parentChainBlockRootInfo }; var tree = block.Body.BinaryMerkleTreeForSideChainTransactionRoots; var pathForTx1 = bmt1.GenerateMerklePath(0); Assert.Equal(root1, pathForTx1.ComputeRootWith(t1.GetHash())); var pathForSc1Block = tree.GenerateMerklePath(0); pathForTx1.Path.AddRange(pathForSc1Block.Path); var pathForTx2 = bmt2.GenerateMerklePath(0); var pathForSc2Block = tree.GenerateMerklePath(1); pathForTx2.Path.AddRange(pathForSc2Block.Path); //parentChainBlockInfo.IndexedBlockInfo.Add(1, tree.GenerateMerklePath(0)); await _contract.WriteParentChainBLockInfo(parentChainBlockInfo); //crossChainInfo = new CrossChainInfo(Mock.StateStore); parentHeight = crossChainInfo.GetParentChainCurrentHeight(); Assert.Equal(pHeight, parentHeight); var b = await _contract.VerifyTransaction(t1.GetHash(), pathForTx1, parentChainBlockRootInfo.Height); Assert.True(b); b = await _contract.VerifyTransaction(t2.GetHash(), pathForTx2, parentChainBlockRootInfo.Height); Assert.True(b); }
private async Task <BlockValidationResult> DPoSValidation(IBlock block, IChainContext context) { // If the height of chain is 1, no need to check consensus validation if (block.Header.Index < GlobalConfig.GenesisBlockHeight + 2) { return(BlockValidationResult.Success); } // Get BP address var uncompressedPrivateKey = block.Header.P.ToByteArray(); var recipientKeyPair = ECKeyPair.FromPublicKey(uncompressedPrivateKey); var address = recipientKeyPair.GetAddress().DumpHex(); // Get the address of consensus contract var contractAccountHash = AddressHelpers.GetSystemContractAddress(context.ChainId, SmartContractType.AElfDPoS.ToString()); var timestampOfBlock = block.Header.Time; long roundId = 1; var updateTx = block.Body.TransactionList.Where(t => t.MethodName == ConsensusBehavior.UpdateAElfDPoS.ToString()) .ToList(); if (updateTx.Count > 0) { if (updateTx.Count > 1) { return(BlockValidationResult.IncorrectDPoSTxInBlock); } roundId = ((Round)ParamsPacker.Unpack(updateTx[0].Params.ToByteArray(), new[] { typeof(Round), typeof(Round), typeof(StringValue) })[1]).RoundId; } //Formulate an Executive and execute a transaction of checking time slot of this block producer TransactionTrace trace; var executive = await _smartContractService.GetExecutiveAsync(contractAccountHash, context.ChainId); try { var tx = GetTxToVerifyBlockProducer(contractAccountHash, NodeConfig.Instance.ECKeyPair, address, timestampOfBlock, roundId); if (tx == null) { return(BlockValidationResult.FailedToCheckConsensusInvalidation); } var tc = new TransactionContext { Transaction = tx }; await executive.SetTransactionContext(tc).Apply(); trace = tc.Trace; } finally { _smartContractService.PutExecutiveAsync(contractAccountHash, executive).Wait(); } //If failed to execute the transaction of checking time slot if (!trace.StdErr.IsNullOrEmpty()) { _logger.Trace("Failed to execute tx Validation: " + trace.StdErr); return(BlockValidationResult.FailedToCheckConsensusInvalidation); } var result = Int32Value.Parser.ParseFrom(trace.RetVal.ToByteArray()).Value; switch (result) { case 1: return(BlockValidationResult.NotBP); case 2: return(BlockValidationResult.InvalidTimeSlot); case 3: return(BlockValidationResult.SameWithCurrentRound); case 11: return(BlockValidationResult.ParseProblem); default: return(BlockValidationResult.Success); } }
public List <Transaction> CreateTxs(Hash chainId) { var contractAddressZero = AddressHelpers.GetSystemContractAddress(chainId, GlobalConfig.GenesisBasicContract); var code = ExampleContractCode; ECKeyPair keyPair = new KeyPairGenerator().Generate(); ECSigner signer = new ECSigner(); var txnDep = new Transaction() { From = keyPair.GetAddress(), To = contractAddressZero, IncrementId = 0, MethodName = "DeploySmartContract", Params = ByteString.CopyFrom(ParamsPacker.Pack((int)0, code)), Fee = TxPoolConfig.Default.FeeThreshold + 1, Type = TransactionType.ContractTransaction }; Hash hash = txnDep.GetHash(); ECSignature signature1 = signer.Sign(keyPair, hash.DumpByteArray()); txnDep.Sig = new Signature { P = ByteString.CopyFrom(keyPair.PublicKey.Q.GetEncoded()), R = ByteString.CopyFrom(signature1.R), S = ByteString.CopyFrom(signature1.S), }; var txInv_1 = new Transaction { From = keyPair.GetAddress(), To = contractAddressZero, IncrementId = 1, MethodName = "Print", Params = ByteString.CopyFrom(ParamsPacker.Pack("AElf")), Fee = TxPoolConfig.Default.FeeThreshold + 1, Type = TransactionType.ContractTransaction }; ECSignature signature2 = signer.Sign(keyPair, txInv_1.GetHash().DumpByteArray()); txInv_1.Sig = new Signature { P = ByteString.CopyFrom(keyPair.PublicKey.Q.GetEncoded()), R = ByteString.CopyFrom(signature2.R), S = ByteString.CopyFrom(signature2.S) }; var txInv_2 = new Transaction { From = keyPair.GetAddress(), To = contractAddressZero, IncrementId = txInv_1.IncrementId, MethodName = "Print", Params = ByteString.CopyFrom(ParamsPacker.Pack("AElf")), Fee = TxPoolConfig.Default.FeeThreshold + 1, Type = TransactionType.ContractTransaction }; ECSignature signature3 = signer.Sign(keyPair, txInv_2.GetHash().DumpByteArray()); txInv_2.Sig = new Signature { P = ByteString.CopyFrom(keyPair.PublicKey.Q.GetEncoded()) }; txInv_2.Sig.R = ByteString.CopyFrom(signature3.R); txInv_2.Sig.S = ByteString.CopyFrom(signature3.S); var txs = new List <Transaction>() { txnDep, txInv_1, txInv_2 }; return(txs); }
public static Address GetSideChainContractAddress() { return(AddressHelpers.GetSystemContractAddress(_smartContractContext.ChainId, SmartContractType.SideChainContract.ToString())); }
public static Address GetContractZeroAddress() { return(AddressHelpers.GetSystemContractAddress(_smartContractContext.ChainId, GlobalConfig.GenesisBasicContract)); }