예제 #1
0
 public DPoSTriggerInformation GetTriggerInformationForNextRoundOrTerm(string publicKey, Timestamp timestamp, bool isBootMiner = true)
 {
     return(new DPoSTriggerInformation
     {
         PublicKey = ByteString.CopyFrom(ByteArrayHelpers.FromHexString(publicKey))
     });
 }
예제 #2
0
        public PeerManager(IConnectionListener connectionListener, IChainService chainService, ILogger logger)
        {
            _jobQueue    = new BlockingCollection <PeerManagerJob>();
            _bpAddresses = new List <byte[]>();
            _whiteList   = new List <byte[]>();

            _connectionListener = connectionListener;
            _chainService       = chainService;
            //_blockChain = blockChain;
            _logger = logger;

            _nodeName = NodeConfig.Instance.NodeName;

            if (!string.IsNullOrWhiteSpace(NetworkConfig.Instance.NetAllowed))
            {
                if (Enum.TryParse(NetworkConfig.Instance.NetAllowed, out AllowedConnection myName))
                {
                    _allowedConnections = myName;
                }
            }

            if (NetworkConfig.Instance.NetWhitelist != null)
            {
                foreach (var peer in NetworkConfig.Instance.NetWhitelist)
                {
                    _whiteList.Add(ByteArrayHelpers.FromHexString(peer));
                }
            }

            SetBpConfig();
        }
예제 #3
0
        private async Task <string[]> PublishTransactionsAsync(string[] rawTransactions)
        {
            var txIds        = new string[rawTransactions.Length];
            var transactions = new List <Transaction>();

            for (var i = 0; i < rawTransactions.Length; i++)
            {
                Transaction transaction;
                try
                {
                    var hexString = ByteArrayHelpers.FromHexString(rawTransactions[i]);
                    transaction = Transaction.Parser.ParseFrom(hexString);
                }
                catch
                {
                    throw new UserFriendlyException(Error.Message[Error.InvalidTransaction], Error.InvalidTransaction.ToString());
                }

                if (!transaction.VerifySignature())
                {
                    throw new UserFriendlyException(Error.Message[Error.InvalidTransaction], Error.InvalidTransaction.ToString());
                }

                transactions.Add(transaction);
                txIds[i] = transaction.GetHash().ToHex();
            }

            await LocalEventBus.PublishAsync(new TransactionsReceivedEvent()
            {
                Transactions = transactions
            });

            return(txIds);
        }
예제 #4
0
        public async Task Call_ReadOnly_Success()
        {
            // Generate a transaction
            var chain = await _blockchainService.GetChainAsync();

            var basicContractZero = _smartContractAddressService.GetZeroSmartContractAddress();
            var transaction       = new Transaction
            {
                From       = Address.Generate(),
                To         = basicContractZero,
                MethodName = "GetContractInfo",
                Params     = basicContractZero.ToByteString()
            };

            var response = await JsonCallAsJObject("/chain", "Call",
                                                   new { rawTransaction = transaction.ToByteArray().ToHex() });

            var resultString = response["result"].ToString();

            resultString.ShouldNotBeNullOrEmpty();

            var bs           = ByteArrayHelpers.FromHexString(resultString);
            var contractInfo = ContractInfo.Parser.ParseFrom(bs);

            contractInfo.ShouldNotBeNull();
        }
예제 #5
0
        public void MerkleProofTest_MultiLeaves()
        {
            var tree = new BinaryMerkleTree();

            string hex1  = "5a7d71da020cae179a0dfe82bd3c967e1573377578f4cc87bc21f74f2556c0ef";
            var    hash1 = CreateLeafFromHex(hex1);

            string hex2  = "a28bf94d0491a234d1e99abc62ed344eb55bb11aeecacc35c1b75bfa85c8983f";
            var    hash2 = CreateLeafFromHex(hex2);

            string hex3  = "bf6ae8809d017f07b27ad1620839c6503666fb55f7fe7ac70881e8864ce5a3ff";
            var    hash3 = CreateLeafFromHex(hex3);

            string hex4  = "bac4adcf8066921237320cdcddb721f5ba5d34065b9c54fe7f9893d8dfe52f17";
            var    hash4 = CreateLeafFromHex(hex4);

            string hex5  = "bac4adcf8066921237320cdcddb721f5ba5d34065b9c54fe7f9893d8dfe52f17";
            var    hash5 = Hash.FromRawBytes(ByteArrayHelpers.FromHexString(hex5)
                                             .Concat(Encoding.UTF8.GetBytes(TransactionResultStatus.Mined.ToString())).ToArray());

            tree.AddNodes(new [] { hash1, hash2, hash3, hash4, hash5 });

            //See if the hash of merkle tree is equal to the element’s hash.
            var root           = tree.ComputeRootHash();
            var path           = tree.GenerateMerklePath(4);
            var calculatedRoot = path.ComputeRootWith(hash5);

            //Assert.Contains(hash3, path.Path);
            Assert.Equal(root, calculatedRoot);
        }
예제 #6
0
        public async Task <JObject> ProcessCallReadOnly(string raw64)
        {
            var hexString   = ByteArrayHelpers.FromHexString(raw64);
            var transaction = Transaction.Parser.ParseFrom(hexString);

            JObject response;

            try
            {
                var res = await this.CallReadOnly(transaction);

                response = new JObject
                {
                    ["return"] = res.ToHex()
                };
            }
            catch (Exception e)
            {
                response = new JObject
                {
                    ["error"] = e.ToString()
                };
            }

            return(JObject.FromObject(response));
        }
예제 #7
0
        public async Task <JObject> SignHash(string address, string password, string hash)
        {
            var tryOpen = KeyStore.OpenAsync(address, password);

            if (tryOpen == AElfKeyStore.Errors.WrongPassword)
            {
                return(new JObject()
                {
                    ["error"] = "Wrong password."
                });
            }

            ECKeyPair kp = KeyStore.GetAccountKeyPair(address);

            byte[] toSig = ByteArrayHelpers.FromHexString(hash);
            // Sign the hash
            ECSigner    signer    = new ECSigner();
            ECSignature signature = signer.Sign(kp, toSig);

            // TODO: Standardize encoding
            return(new JObject()
            {
                ["R"] = signature.R,
                ["S"] = signature.S,
                ["P"] = kp.PublicKey.Q.GetEncoded()
            });
        }
예제 #8
0
 public void Deserialize()
 {
     var bytes = ByteArrayHelpers.FromHexString(
         "0a200a1e9dee15619106b96861d52f03ad30ac7e57aa529eb2f05f7796472d8ce4a112200a1e96d8bf2dccf2ad419d02ed4a7b7a9d77df10617c4d731e766ce8dde63535320a496e697469616c697a653a0a0a015b120122180020005003");
     var    txBytes = ByteString.CopyFrom(bytes).ToByteArray();
     var    txn     = Transaction.Parser.ParseFrom(txBytes);
     string str     = txn.From.Value.ToByteArray().ToHex();
 }
예제 #9
0
 private DPoSTriggerInformation GetTriggerInformationForNextTerm(string publicKey)
 {
     return(new DPoSTriggerInformation
     {
         PublicKey = ByteString.CopyFrom(ByteArrayHelpers.FromHexString(publicKey)),
         Behaviour = DPoSBehaviour.NextTerm
     });
 }
예제 #10
0
//
//        public static Hash GetMinersHash(this Miners miners)
//        {
//            var orderedMiners = miners.PublicKeys.OrderBy(p => p);
//            return Hash.FromString(orderedMiners.Aggregate("", (current, publicKey) => current + publicKey));
//        }
//
//        public static long GetMinedBlocks(this Round round)
//        {
//            return round.RealTimeMinersInformation.Values.Sum(minerInRound => minerInRound.ProducedBlocks);
//        }
//
//        public static void AddCandidate(this Candidates candidates, byte[] publicKey)
//        {
//            candidates.PublicKeys.Add(publicKey.ToHex());
//            candidates.Addresses.Add(Address.FromPublicKey(publicKey));
//        }
//
//        public static bool RemoveCandidate(this Candidates candidates, byte[] publicKey)
//        {
//            var result1 = candidates.PublicKeys.Remove(publicKey.ToHex());
//            var result2 = candidates.Addresses.Remove(Address.FromPublicKey(publicKey));
//            return result1 && result2;
//        }
//
//        public static bool IsExpired(this VotingRecord votingRecord, long currentAge)
//        {
//            var lockExpiredAge = votingRecord.VoteAge;
//            foreach (var day in votingRecord.LockDaysList)
//            {
//                lockExpiredAge += day;
//            }
//
//            return lockExpiredAge <= currentAge;
//        }

        public static Miners ToMiners(this List <string> minerPublicKeys, long termNumber = 0)
        {
            return(new Miners
            {
                PublicKeys = { minerPublicKeys },
                Addresses = { minerPublicKeys.Select(p => Address.FromPublicKey(ByteArrayHelpers.FromHexString(p))) },
                TermNumber = termNumber
            });
        }
예제 #11
0
 static SampleECKeyPairs()
 {
     KeyPairs = new ReadOnlyCollection <ECKeyPair>(
         _keys.Select(x =>
     {
         var privateKeyHex = x.Split(",").First();
         var privateKey    = ByteArrayHelpers.FromHexString(privateKeyHex);
         return(CryptoHelpers.FromPrivateKey(privateKey));
     }).ToList());
 }
예제 #12
0
 private void SetInitialMinersHistory(IEnumerable <string> initialMinersPublicKeys)
 {
     foreach (var initialMinerPublicKey in initialMinersPublicKeys)
     {
         State.HistoryMap[initialMinerPublicKey.ToStringValue()] = new CandidateInHistory
         {
             PublicKey = initialMinerPublicKey,
             Address   = Address.FromPublicKey(ByteArrayHelpers.FromHexString(initialMinerPublicKey))
         };
     }
 }
예제 #13
0
        private Hash GetHashFromHexString(params string[] strings)
        {
            var hash = Hash.LoadByteArray(ByteArrayHelpers.FromHexString(strings[0]));

            foreach (var s in strings.Skip(1))
            {
                hash = Hash.FromRawBytes(hash.DumpByteArray().Concat(ByteArrayHelpers.FromHexString(s)).ToArray());
            }

            return(hash);
        }
예제 #14
0
        public override string GetPrintString(JObject resp)
        {
            JToken ss = resp["abi"];

            byte[] aa = ByteArrayHelpers.FromHexString(ss.ToString());

            MemoryStream ms = new MemoryStream(aa);
            Module       m  = Serializer.Deserialize <Module>(ms);

            return(JsonConvert.SerializeObject(m));
        }
예제 #15
0
        public async Task <JObject> GetDbValue(string key)
        {
            string type = string.Empty;
            JToken id;

            try
            {
                object value;

                if (key.StartsWith(GlobalConfig.StatePrefix))
                {
                    type = "State";
                    id   = key.Substring(GlobalConfig.StatePrefix.Length, key.Length - GlobalConfig.StatePrefix.Length);
                    var valueBytes = KeyValueDatabase.GetAsync(type, key).Result;
                    value = StateValue.Create(valueBytes);
                }
                else if (key.StartsWith(GlobalConfig.TransactionReceiptPrefix))
                {
                    type = "TransactionReceipt";
                    id   = key.Substring(GlobalConfig.TransactionReceiptPrefix.Length, key.Length - GlobalConfig.TransactionReceiptPrefix.Length);
                    var valueBytes = KeyValueDatabase.GetAsync(type, key).Result;
                    value = valueBytes?.Deserialize <TransactionReceipt>();
                }
                else
                {
                    var keyObj = Key.Parser.ParseFrom(ByteArrayHelpers.FromHexString(key));
                    type = keyObj.Type;
                    id   = JObject.Parse(keyObj.ToString());
                    var valueBytes = KeyValueDatabase.GetAsync(type, key).Result;
                    var obj        = this.GetInstance(type);
                    obj.MergeFrom(valueBytes);
                    value = obj;
                }

                var response = new JObject
                {
                    ["Type"]  = type,
                    ["Id"]    = id,
                    ["Value"] = JObject.Parse(value.ToString())
                };

                return(JObject.FromObject(response));
            }
            catch (Exception e)
            {
                var response = new JObject
                {
                    ["Type"]  = type,
                    ["Value"] = e.Message
                };
                return(JObject.FromObject(response));
            }
        }
예제 #16
0
        public void Convert_Byte_FromString()
        {
            var hexValue  = Hash.Generate().ToHex();
            var hashArray = ByteArrayHelpers.FromHexString(hexValue);

            hashArray.Length.ShouldBe(32);

            var value       = "0x00";
            var valueArrary = ByteArrayHelpers.FromHexString(value);

            valueArrary.Length.ShouldBe(1);
        }
        public override Empty commentEvent(CommentEventAddress input)
        {
            //send postive score to comment sender
            State.TokenContract.Transfer.Send(new AElf.Contracts.MultiToken.Messages.TransferInput {
                To     = Address.FromBytes(ByteArrayHelpers.FromHexString(input.SenderCommentAdd)),
                Symbol = score_participate_positive,
                Amount = comment_score_sender,
                Memo   = input.CommentContent
            });


            return(new Empty());
        }
        public override Empty middleTransfer(MiddleTransInfo input)
        {
            //send postive score to comment sender
            State.TokenContract.Transfer.Send(new AElf.Contracts.MultiToken.Messages.TransferInput {
                To     = Address.FromBytes(ByteArrayHelpers.FromHexString(input.To)),
                Symbol = input.MySymbol,
                Amount = input.Amount,
                Memo   = "记事本"
            });


            return(new Empty());
        }
예제 #19
0
 private Transaction ConvertFromJson(JObject j)
 {
     try
     {
         Transaction tr = new Transaction();
         tr.From       = ByteArrayHelpers.FromHexString(j["from"].ToString());
         tr.To         = ByteArrayHelpers.FromHexString(j["to"].ToString());
         tr.MethodName = j["method"].ToObject <string>();
         return(tr);
     }
     catch (Exception e)
     {
         throw new InvalidTransactionException();
     }
 }
예제 #20
0
        public DPoSTriggerInformation GetTriggerInformationForNormalBlock(string publicKey, Hash randomHash,
                                                                          Hash previousRandomHash = null)
        {
            if (previousRandomHash == null)
            {
                previousRandomHash = Hash.Empty;
            }

            return(new DPoSTriggerInformation
            {
                PublicKey = ByteString.CopyFrom(ByteArrayHelpers.FromHexString(publicKey)),
                PreviousRandomHash = previousRandomHash,
                RandomHash = randomHash
            });
        }
예제 #21
0
        private SystemContractDeploymentInput.Types.SystemTransactionMethodCallList GenerateTokenInitializationCallList(
            Address issuer)
        {
            var tokenContractCallList = new SystemContractDeploymentInput.Types.SystemTransactionMethodCallList();

            tokenContractCallList.Add(nameof(TokenContract.CreateNativeToken), new CreateNativeTokenInput
            {
                Symbol      = _tokenInitialOptions.Symbol,
                Decimals    = _tokenInitialOptions.Decimals,
                IsBurnable  = _tokenInitialOptions.IsBurnable,
                TokenName   = _tokenInitialOptions.Name,
                TotalSupply = _tokenInitialOptions.TotalSupply,
                // Set the contract zero address as the issuer temporarily.
                Issuer = issuer,
                LockWhiteSystemContractNameList = { ConsensusSmartContractAddressNameProvider.Name }
            });

            tokenContractCallList.Add(nameof(TokenContract.IssueNativeToken), new IssueNativeTokenInput
            {
                Symbol = _tokenInitialOptions.Symbol,
                Amount = (long)(_tokenInitialOptions.TotalSupply * _tokenInitialOptions.DividendPoolRatio),
                ToSystemContractName = DividendSmartContractAddressNameProvider.Name,
                Memo = "Set dividends.",
            });

            //TODO: Maybe should be removed after testing.
            foreach (var tokenReceiver in _dposOptions.InitialMiners)
            {
                tokenContractCallList.Add(nameof(TokenContract.Issue), new IssueInput
                {
                    Symbol = _tokenInitialOptions.Symbol,
                    Amount = (long)(_tokenInitialOptions.TotalSupply * (1 - _tokenInitialOptions.DividendPoolRatio)) /
                             _dposOptions.InitialMiners.Count,
                    To   = Address.FromPublicKey(ByteArrayHelpers.FromHexString(tokenReceiver)),
                    Memo = "Set initial miner's balance.",
                });
            }

            // Set fee pool address to dividend contract address.
            tokenContractCallList.Add(nameof(TokenContract.SetFeePoolAddress),
                                      DividendSmartContractAddressNameProvider.Name);

            tokenContractCallList.Add(nameof(TokenContract.InitializeTokenContract), new IntializeTokenContractInput
            {
                CrossChainContractSystemName = CrossChainSmartContractAddressNameProvider.Name
            });
            return(tokenContractCallList);
        }
예제 #22
0
        public override ElectionTickets GetTicketsInformation(StringInput input)
        {
            var votingRecords = State.VoteContract.GetVotingHistory.Call(new GetVotingHistoryInput
            {
                Topic   = ElectionContractConsts.Topic,
                Sponsor = Context.Self,
                Voter   = Address.FromPublicKey(ByteArrayHelpers.FromHexString(input.Value))
            });

            var electionTickets = new ElectionTickets
            {
                PublicKey = input.Value,
            };

            return(electionTickets);
        }
예제 #23
0
        public async Task <string> CallReadOnly(string rawTransaction)
        {
            byte[] response;
            try
            {
                var hexString   = ByteArrayHelpers.FromHexString(rawTransaction);
                var transaction = Transaction.Parser.ParseFrom(hexString);
                response = await this.CallReadOnly(transaction);
            }
            catch
            {
                throw new JsonRpcServiceException(Error.InvalidTransaction, Error.Message[Error.InvalidTransaction]);
            }

            return(response?.ToHex());
        }
예제 #24
0
        public void RpcGetContractAbi(CommandInfo ci)
        {
            if (ci.Parameter == "")
            {
                if (_genesisAddress == null)
                {
                    ci.ErrorMsg.Add("Please connect_chain first.");
                    return;
                }
                ci.Parameter = _genesisAddress;
            }

            var req = RpcRequestManager.CreateRequest(new JObject
            {
                ["address"] = ci.Parameter
            }, ci.Category, 1);

            Module m = null;

            if (!_loadedModules.TryGetValue(ci.Parameter, out m))
            {
                string returnCode = string.Empty;
                long   timeSpan   = 0;
                string resp       = _requestManager.PostRequest(req.ToString(), out returnCode, out timeSpan);
                ci.TimeSpan = timeSpan;
                if (!CheckResponse(ci, returnCode, resp))
                {
                    return;
                }

                JObject jObj = JObject.Parse(resp);
                var     res  = JObject.FromObject(jObj["result"]);

                JToken ss = res["abi"];
                byte[] aa = ByteArrayHelpers.FromHexString(ss.ToString());

                MemoryStream ms = new MemoryStream(aa);
                m = Serializer.Deserialize <Module>(ms);
                _loadedModules.Add(ci.Parameter, m);
                ci.InfoMsg.Add(resp);
            }

            var obj = JObject.FromObject(m);

            ci.InfoMsg.Add(obj.ToString());
            ci.Result = true;
        }
예제 #25
0
        public void MerkleProofTest()
        {
            var tree = new BinaryMerkleTree();

            string hex = "5a7d71da020cae179a0dfe82bd3c967e1573377578f4cc87bc21f74f2556c0ef";

            tree.AddNode(CreateLeafFromHex(hex));

            //See if the hash of merkle tree is equal to the element’s hash.
            var root           = tree.ComputeRootHash();
            var path           = tree.GenerateMerklePath(0);
            var hash           = Hash.LoadByteArray(ByteArrayHelpers.FromHexString(hex));
            var calculatedRoot = path.ComputeRootWith(hash);

            Assert.Contains(hash, path.Path);
            Assert.Equal(root, calculatedRoot);
        }
예제 #26
0
        private SystemContractDeploymentInput.Types.SystemTransactionMethodCallList GenerateTokenInitializationCallList(
            Address issuer, List <string> tokenReceivers)
        {
            const int totalSupply           = 10_0000_0000;
            var       tokenContractCallList = new SystemContractDeploymentInput.Types.SystemTransactionMethodCallList();

            tokenContractCallList.Add(nameof(TokenContract.CreateNativeToken), new CreateNativeTokenInput
            {
                Symbol      = Symbol,
                Decimals    = 2,
                IsBurnable  = true,
                TokenName   = "elf token",
                TotalSupply = totalSupply,
                Issuer      = issuer,
                LockWhiteSystemContractNameList =
                {
                    ElectionSmartContractAddressNameProvider.Name,
                    ProfitSmartContractAddressNameProvider.Name,
                    VoteSmartContractAddressNameProvider.Name
                }
            });

            tokenContractCallList.Add(nameof(TokenContract.IssueNativeToken), new IssueNativeTokenInput
            {
                Symbol = Symbol,
                Amount = totalSupply.Mul(2).Div(10),
                ToSystemContractName = ElectionSmartContractAddressNameProvider.Name,
                Memo = "Set dividends."
            });

            foreach (var tokenReceiver in tokenReceivers)
            {
                tokenContractCallList.Add(nameof(TokenContract.Issue), new IssueInput
                {
                    Symbol = Symbol,
                    Amount = (long)(totalSupply * 0.8) / tokenReceivers.Count,
                    To     = Address.FromPublicKey(ByteArrayHelpers.FromHexString(tokenReceiver)),
                    Memo   = "Set initial miner's balance.",
                });
            }

            // Set fee pool address to the address of contract in charge of profit item of tx fee.
            tokenContractCallList.Add(nameof(TokenContract.SetFeePoolAddress),
                                      ElectionSmartContractAddressNameProvider.Name);
            return(tokenContractCallList);
        }
예제 #27
0
        public static Transaction AddBlockReference(this Transaction transaction, string rpcAddress)
        {
            var height = _cachedHeight;
            var hash   = _cachedHash;

            if (height == default(ulong) || (DateTime.Now - _refBlockTime).TotalSeconds > 60)
            {
                height        = ulong.Parse(GetBlkHeight(rpcAddress));
                hash          = GetBlkHash(rpcAddress, height.ToString());
                _cachedHeight = height;
                _cachedHash   = hash;
                _refBlockTime = DateTime.Now;
            }
            transaction.RefBlockNumber = height;
            transaction.RefBlockPrefix = ByteArrayHelpers.FromHexString(hash).Where((b, i) => i < 4).ToArray();
            return(transaction);
        }
예제 #28
0
 private Transaction CreateTransaction(string elementAt, string genesisAddress,
                                       string methodName, byte[] serializedParams, TransactionType contracttransaction)
 {
     try
     {
         Transaction t = new Transaction();
         t.From       = ByteArrayHelpers.FromHexString(elementAt);
         t.To         = ByteArrayHelpers.FromHexString(genesisAddress);
         t.MethodName = methodName;
         t.Params     = serializedParams;
         t.type       = contracttransaction;
         return(t);
     }
     catch (Exception e)
     {
         throw new InvalidTransactionException();
     }
 }
예제 #29
0
        internal T GetValue <T>()
        {
            if (typeof(T) == typeof(bool))
            {
                return((T)(object)true);
            }

            if (typeof(T) == typeof(int))
            {
                return((T)(object)(int)-12345);
            }

            if (typeof(T) == typeof(uint))
            {
                return((T)(object)(uint)12345U);
            }

            if (typeof(T) == typeof(long))
            {
                return((T)(object)(long)-678910L);
            }

            if (typeof(T) == typeof(ulong))
            {
                return((T)(object)(ulong)678910UL);
            }

            if (typeof(T) == typeof(byte[]))
            {
                return((T)(object)ByteArrayHelpers.FromHexString("302010"));
            }

            if (typeof(T) == typeof(string))
            {
                return((T)(object)"aelf");
            }

            if (typeof(T) == typeof(Address))
            {
                return((T)(object)Address.FromString("a"));
            }

            throw new Exception("Not supported type.");
        }
예제 #30
0
        /// <summary>
        /// Call a read-only method on a contract.
        /// </summary>
        /// <param name="rawTransaction">raw transaction</param>
        /// <returns></returns>
        public async Task <string> Call(string rawTransaction)
        {
            try
            {
                var hexString   = ByteArrayHelpers.FromHexString(rawTransaction);
                var transaction = Transaction.Parser.ParseFrom(hexString);
                if (!transaction.VerifySignature())
                {
                    throw new UserFriendlyException(Error.Message[Error.InvalidTransaction], Error.InvalidTransaction.ToString());
                }
                var response = await CallReadOnly(transaction);

                return(response?.ToHex());
            }
            catch
            {
                throw new UserFriendlyException(Error.Message[Error.InvalidTransaction], Error.InvalidTransaction.ToString());
            }
        }