示例#1
0
        public void Recover_Public_Key_Test()
        {
            var keyPair = CryptoHelper.GenerateKeyPair();

            var messageBytes1 = Encoding.UTF8.GetBytes("Hello world.");
            var messageHash1  = messageBytes1.ComputeHash();

            var messageBytes2 = Encoding.UTF8.GetBytes("Hello aelf.");
            var messageHash2  = messageBytes2.ComputeHash();

            var signature1 = CryptoHelper.SignWithPrivateKey(keyPair.PrivateKey, messageHash1);

            var recoverResult1 = CryptoHelper.RecoverPublicKey(signature1, messageHash1, out var publicKey1);

            Assert.True(recoverResult1);
            Assert.True(publicKey1.BytesEqual(keyPair.PublicKey));

            var recoverResult2 = CryptoHelper.RecoverPublicKey(signature1, messageHash2, out var publicKey2);

            Assert.True(recoverResult2);
            Assert.False(publicKey2.BytesEqual(keyPair.PublicKey));

            var invalidSignature = ByteArrayHelper.HexStringToByteArray(
                "1c9469cbd4b9f722056d3eafd9823b14be9d2759192a7980aafba9d767576834ce25cb570e63dede117ff5c831e33ac47d0450b6b4cea0d04d66a435f2275ef3ec");
            var recoverResult3 = CryptoHelper.RecoverPublicKey(invalidSignature, messageHash2, out var publicKey3);

            Assert.False(recoverResult3);

            var invalidSignature2 = new byte[10];
            var recoverResult4    = CryptoHelper.RecoverPublicKey(invalidSignature2, messageHash2, out var publicKey4);

            Assert.False(recoverResult4);
        }
        /// <summary>
        /// Update the candidate information,if it's not evil node.
        /// </summary>
        /// <param name="input">UpdateCandidateInformationInput</param>
        /// <returns></returns>
        public override Empty UpdateCandidateInformation(UpdateCandidateInformationInput input)
        {
            var candidateInformation = State.CandidateInformationMap[input.Pubkey];

            if (input.IsEvilNode)
            {
                var publicKeyByte = ByteArrayHelper.HexStringToByteArray(input.Pubkey);
                State.BlackList.Value.Value.Add(ByteString.CopyFrom(publicKeyByte));
                State.ProfitContract.RemoveBeneficiary.Send(new RemoveBeneficiaryInput
                {
                    SchemeId    = State.SubsidyHash.Value,
                    Beneficiary = Address.FromPublicKey(publicKeyByte)
                });
                Context.LogDebug(() => $"Marked {input.Pubkey.Substring(0, 10)} as an evil node.");
                // TODO: Set to null.
                State.CandidateInformationMap[input.Pubkey] = new CandidateInformation();
                var candidates = State.Candidates.Value;
                candidates.Value.Remove(ByteString.CopyFrom(publicKeyByte));
                State.Candidates.Value = candidates;
                return(new Empty());
            }

            candidateInformation.ProducedBlocks  = candidateInformation.ProducedBlocks.Add(input.RecentlyProducedBlocks);
            candidateInformation.MissedTimeSlots =
                candidateInformation.MissedTimeSlots.Add(input.RecentlyMissedTimeSlots);
            State.CandidateInformationMap[input.Pubkey] = candidateInformation;
            return(new Empty());
        }
示例#3
0
        private ByteString GetSignatureWith(string privateKey, byte[] txData)
        {
            // Sign the hash
            var signature = CryptoHelper.SignWithPrivateKey(ByteArrayHelper.HexStringToByteArray(privateKey), txData);

            return(ByteString.CopyFrom(signature));
        }
示例#4
0
        public override List <ContractInitializationMethodCall> GetInitializeMethodList(byte[] contractCode)
        {
            var address = Address.FromPublicKey(
                ByteArrayHelper.HexStringToByteArray(_consensusOptions.InitialMinerList[0]));
            var list = new List <ContractInitializationMethodCall>
            {
                new ContractInitializationMethodCall
                {
                    MethodName = nameof(TokenContractImplContainer.TokenContractImplStub.Create),
                    Params     = new CreateInput
                    {
                        Decimals     = _economicOptions.Decimals,
                        Issuer       = address,
                        IsBurnable   = _economicOptions.IsBurnable,
                        Symbol       = _economicOptions.Symbol,
                        TokenName    = _economicOptions.TokenName,
                        TotalSupply  = _economicOptions.TotalSupply,
                        IsProfitable = true
                    }.ToByteString(),
                },
                new ContractInitializationMethodCall
                {
                    MethodName = nameof(TokenContractImplContainer.TokenContractImplStub.Issue),
                    Params     = new IssueInput
                    {
                        Symbol = _economicOptions.Symbol,
                        Amount = Convert.ToInt64(_economicOptions.TotalSupply * (1 - _economicOptions.DividendPoolRatio)),
                        To     = address,
                        Memo   = "Issue native token"
                    }.ToByteString()
                }
            };

            return(list);
        }
        public void CalculateHashTest(string address, string amount, string uid, string result)
        {
            var hashFromString = HashHelper.ComputeFrom(address);

            var parsedResult          = decimal.Parse(amount);
            var originTokenSizeInByte = 32;
            var preHolderSize         = originTokenSizeInByte - 16;
            var bytesFromDecimal      = decimal.GetBits(parsedResult).Reverse().ToArray();

            if (preHolderSize < 0)
            {
                bytesFromDecimal = bytesFromDecimal.TakeLast(originTokenSizeInByte).ToArray();
            }

            var amountBytes = new List <byte>();

            bytesFromDecimal.Aggregate(amountBytes, (cur, i) =>
            {
                while (cur.Count < preHolderSize)
                {
                    cur.Add(new byte());
                }

                cur.AddRange(i.ToBytes());
                return(cur);
            });
            var hashFromAmount = HashHelper.ComputeFrom(amountBytes.ToArray());
            var hashFromUid    = Hash.LoadFromByteArray(ByteArrayHelper.HexStringToByteArray(uid));
            var hash           = HashHelper.ConcatAndCompute(hashFromAmount, hashFromString, hashFromUid);

            Assert.True(hash == Hash.LoadFromByteArray(ByteArrayHelper.HexStringToByteArray(result)));
        }
示例#6
0
        private void AddBeneficiariesForReElectionScheme(long endPeriod, IEnumerable <string> victories,
                                                         MinerReElectionInformation minerReElectionInformation)
        {
            var reElectionProfitAddBeneficiaries = new AddBeneficiariesInput
            {
                SchemeId  = State.ReElectionRewardHash.Value,
                EndPeriod = endPeriod
            };

            foreach (var victory in victories)
            {
                if (minerReElectionInformation.ContinualAppointmentTimes.ContainsKey(victory))
                {
                    var minerAddress = Address.FromPublicKey(ByteArrayHelper.HexStringToByteArray(victory));
                    var continualAppointmentCount =
                        minerReElectionInformation.ContinualAppointmentTimes[victory].Add(1);
                    minerReElectionInformation.ContinualAppointmentTimes[victory] = continualAppointmentCount;
                    reElectionProfitAddBeneficiaries.BeneficiaryShares.Add(new BeneficiaryShare
                    {
                        Beneficiary = minerAddress,
                        Shares      = Math.Min(continualAppointmentCount,
                                               TreasuryContractConstants.MaximumReElectionRewardShare)
                    });
                }
                else
                {
                    minerReElectionInformation.ContinualAppointmentTimes.Add(victory, 0);
                }
            }

            if (reElectionProfitAddBeneficiaries.BeneficiaryShares.Any())
            {
                State.ProfitContract.AddBeneficiaries.Send(reElectionProfitAddBeneficiaries);
            }
        }
 public List <ContractInitializationMethodCall> GetInitializeMethodList(byte[] contractCode)
 {
     return(new List <ContractInitializationMethodCall>
     {
         new ContractInitializationMethodCall {
             MethodName = nameof(EconomicContractContainer.EconomicContractStub.InitialEconomicSystem),
             Params = new InitialEconomicSystemInput
             {
                 NativeTokenDecimals = _economicOptions.Decimals,
                 IsNativeTokenBurnable = _economicOptions.IsBurnable,
                 NativeTokenSymbol = _economicOptions.Symbol,
                 NativeTokenName = _economicOptions.TokenName,
                 NativeTokenTotalSupply = _economicOptions.TotalSupply,
                 MiningRewardTotalAmount =
                     Convert.ToInt64(_economicOptions.TotalSupply * _economicOptions.DividendPoolRatio),
                 TransactionSizeFeeUnitPrice = _economicOptions.TransactionSizeFeeUnitPrice
             }.ToByteString()
         },
         new ContractInitializationMethodCall {
             MethodName = nameof(EconomicContractContainer.EconomicContractStub.IssueNativeToken),
             Params = new IssueNativeTokenInput
             {
                 Amount = Convert.ToInt64(_economicOptions.TotalSupply * (1 - _economicOptions.DividendPoolRatio)),
                 To = Address.FromPublicKey(
                     ByteArrayHelper.HexStringToByteArray(_consensusOptions.InitialMinerList.First())),
                 Memo = "Issue native token"
             }.ToByteString()
         }
     });
 }
示例#8
0
        /// <summary>
        /// Call a read-only method on a contract.
        /// </summary>
        /// <returns></returns>
        public async Task <string> ExecuteTransactionAsync(ExecuteTransactionDto input)
        {
            Transaction transaction;

            try
            {
                var byteArray = ByteArrayHelper.HexStringToByteArray(input.RawTransaction);
                transaction = Transaction.Parser.ParseFrom(byteArray);
            }
            catch (Exception e)
            {
                Logger.LogError(e, e.Message); //for debug
                throw new UserFriendlyException(Error.Message[Error.InvalidParams],
                                                Error.InvalidParams.ToString());
            }

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

            try
            {
                var response = await CallReadOnlyAsync(transaction);

                return(response?.ToHex());
            }
            catch (Exception e)
            {
                throw new UserFriendlyException(Error.Message[Error.InvalidTransaction],
                                                Error.InvalidTransaction.ToString(), e.Message);
            }
        }
        /// <summary>
        /// Remove current total shares of Re-Election Reward,
        /// Add shares to re-elected miners based on their continual appointment count.
        /// </summary>
        /// <param name="previousTermInformation"></param>
        /// <param name="victories"></param>
        private void UpdateReElectionRewardWeights(Round previousTermInformation, ICollection <string> victories)
        {
            var previousMinerAddresses = previousTermInformation.RealTimeMinersInformation.Keys
                                         .Select(k => Address.FromPublicKey(ByteArrayHelper.HexStringToByteArray(k))).ToList();
            var reElectionRewardProfitSubBeneficiaries = new RemoveBeneficiariesInput
            {
                SchemeId      = State.ReElectionRewardHash.Value,
                Beneficiaries = { previousMinerAddresses }
            };

            State.ProfitContract.RemoveBeneficiaries.Send(reElectionRewardProfitSubBeneficiaries);

            var minerReElectionInformation = State.MinerReElectionInformation.Value ??
                                             InitialMinerReElectionInformation(previousTermInformation
                                                                               .RealTimeMinersInformation.Keys);

            AddBeneficiariesForReElectionScheme(previousTermInformation.TermNumber.Add(1), victories,
                                                minerReElectionInformation);

            var recordedMiners = minerReElectionInformation.Clone().ContinualAppointmentTimes.Keys;

            foreach (var miner in recordedMiners)
            {
                if (!victories.Contains(miner))
                {
                    minerReElectionInformation.ContinualAppointmentTimes.Remove(miner);
                }
            }

            State.MinerReElectionInformation.Value = minerReElectionInformation;
        }
示例#10
0
        GenerateEconomicInitializationCallList()
        {
            var economicContractMethodCallList =
                new SystemContractDeploymentInput.Types.SystemTransactionMethodCallList();

            economicContractMethodCallList.Add(
                nameof(EconomicContractContainer.EconomicContractStub.InitialEconomicSystem),
                new InitialEconomicSystemInput
            {
                NativeTokenDecimals     = _economicOptions.Decimals,
                IsNativeTokenBurnable   = _economicOptions.IsBurnable,
                NativeTokenSymbol       = _economicOptions.Symbol,
                NativeTokenName         = _economicOptions.TokenName,
                NativeTokenTotalSupply  = _economicOptions.TotalSupply,
                MiningRewardTotalAmount =
                    Convert.ToInt64(_economicOptions.TotalSupply * _economicOptions.DividendPoolRatio),
                TransactionSizeFeeUnitPrice = _economicOptions.TransactionSizeFeeUnitPrice
            });

            //TODO: Maybe should be removed after testing.
            economicContractMethodCallList.Add(
                nameof(EconomicContractContainer.EconomicContractStub.IssueNativeToken), new IssueNativeTokenInput
            {
                Amount = Convert.ToInt64(_economicOptions.TotalSupply * (1 - _economicOptions.DividendPoolRatio)),
                To     = Address.FromPublicKey(
                    ByteArrayHelper.HexStringToByteArray(_consensusOptions.InitialMinerList.First())),
                Memo = "Issue native token"
            });

            return(economicContractMethodCallList);
        }
示例#11
0
        /// <summary>
        /// send a transaction
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task <SendRawTransactionOutput> SendRawTransactionAsync(SendRawTransactionInput input)
        {
            var transaction = Transaction.Parser.ParseFrom(ByteArrayHelper.HexStringToByteArray(input.Transaction));

            transaction.Signature = ByteString.CopyFrom(ByteArrayHelper.HexStringToByteArray(input.Signature));
            var txIds = await PublishTransactionsAsync(new[] { transaction.ToByteArray().ToHex() });

            var output = new SendRawTransactionOutput
            {
                TransactionId = txIds[0]
            };

            if (!input.ReturnTransaction)
            {
                return(output);
            }

            var transactionDto           = JsonConvert.DeserializeObject <TransactionDto>(transaction.ToString());
            var contractMethodDescriptor =
                await GetContractMethodDescriptorAsync(transaction.To, transaction.MethodName);

            var parameters = contractMethodDescriptor.InputType.Parser.ParseFrom(transaction.Params);

            transactionDto.Params = JsonFormatter.ToDiagnosticString(parameters);
            output.Transaction    = transactionDto;

            return(output);
        }
        /// <summary>
        /// Remove current total shares of Basic Reward,
        /// Add new shares for miners of next term.
        /// 1 share for each miner.
        /// </summary>
        /// <param name="previousTermInformation"></param>
        private void UpdateBasicMinerRewardWeights(IReadOnlyCollection <Round> previousTermInformation)
        {
            if (previousTermInformation.First().RealTimeMinersInformation != null)
            {
                State.ProfitContract.RemoveBeneficiaries.Send(new RemoveBeneficiariesInput
                {
                    SchemeId      = State.BasicRewardHash.Value,
                    Beneficiaries =
                    {
                        previousTermInformation.First().RealTimeMinersInformation.Keys.Select(k =>
                                                                                              Address.FromPublicKey(ByteArrayHelper.HexStringToByteArray(k)))
                    }
                });
            }

            // Manage weights of `MinerBasicReward`
            State.ProfitContract.AddBeneficiaries.Send(new AddBeneficiariesInput
            {
                SchemeId          = State.BasicRewardHash.Value,
                EndPeriod         = previousTermInformation.Last().TermNumber,
                BeneficiaryShares =
                {
                    previousTermInformation.Last().RealTimeMinersInformation.Values.Select(i => new BeneficiaryShare
                    {
                        Beneficiary = Address.FromPublicKey(ByteArrayHelper.HexStringToByteArray(i.Pubkey)),
                        Shares      = i.ProducedBlocks
                    })
                }
            });
        }
示例#13
0
        private async Task CollectPiecesWithSecretSharingAsync(SecretSharingInformation secretSharingInformation,
                                                               Hash newInValue, string selfPubkey)
        {
            var encryptedPieces = new Dictionary <string, byte[]>();
            var decryptedPieces = new Dictionary <string, byte[]>();

            var minersCount  = secretSharingInformation.PreviousRound.RealTimeMinersInformation.Count;
            var minimumCount = minersCount.Mul(2).Div(3);
            var secretShares =
                SecretSharingHelper.EncodeSecret(newInValue.ToByteArray(), minimumCount, minersCount);

            foreach (var pair in secretSharingInformation.PreviousRound.RealTimeMinersInformation
                     .OrderBy(m => m.Value.Order).ToDictionary(m => m.Key, m => m.Value.Order))
            {
                var pubkey = pair.Key;
                var order  = pair.Value;

                var plainMessage      = secretShares[order - 1];
                var receiverPublicKey = ByteArrayHelper.HexStringToByteArray(pubkey);
                var encryptedPiece    = await _accountService.EncryptMessageAsync(receiverPublicKey, plainMessage);

                encryptedPieces[pubkey] = encryptedPiece;
                if (secretSharingInformation.PreviousRound.RealTimeMinersInformation.ContainsKey(selfPubkey) &&
                    secretSharingInformation.PreviousRound.RealTimeMinersInformation[selfPubkey].EncryptedPieces
                    .ContainsKey(pubkey))
                {
                    secretSharingInformation.PreviousRound.RealTimeMinersInformation[selfPubkey]
                    .EncryptedPieces[pubkey]
                        = ByteString.CopyFrom(encryptedPiece);
                }
                else
                {
                    continue;
                }

                if (!secretSharingInformation.PreviousRound.RealTimeMinersInformation.ContainsKey(pubkey))
                {
                    continue;
                }

                var encryptedShares =
                    secretSharingInformation.PreviousRound.RealTimeMinersInformation[pubkey].EncryptedPieces;
                if (!encryptedShares.Any())
                {
                    continue;
                }
                var interestingMessage = encryptedShares[selfPubkey];
                var senderPublicKey    = ByteArrayHelper.HexStringToByteArray(pubkey);

                var decryptedPiece =
                    await _accountService.DecryptMessageAsync(senderPublicKey, interestingMessage.ToByteArray());

                decryptedPieces[pubkey] = decryptedPiece;
                secretSharingInformation.PreviousRound.RealTimeMinersInformation[pubkey].DecryptedPieces[selfPubkey]
                    = ByteString.CopyFrom(decryptedPiece);
            }

            _encryptedPieces[secretSharingInformation.CurrentRoundId] = encryptedPieces;
            _decryptedPieces[secretSharingInformation.CurrentRoundId] = decryptedPieces;
        }
示例#14
0
        private void DistributeResourceTokensToPreviousMiners()
        {
            if (State.TokenContract.Value == null)
            {
                State.TokenContract.Value =
                    Context.GetContractAddressByName(SmartContractConstants.TokenContractSystemName);
            }

            var minerList = State.MainChainCurrentMinerList.Value.Pubkeys;

            foreach (var symbol in Context.Variables.ResourceTokenSymbolNameList)
            {
                var balance = State.TokenContract.GetBalance.Call(new GetBalanceInput
                {
                    Owner  = Context.Self,
                    Symbol = symbol
                }).Balance;
                if (balance <= 0)
                {
                    continue;
                }
                var amount = balance.Div(minerList.Count);
                foreach (var pubkey in minerList)
                {
                    var address = Address.FromPublicKey(ByteArrayHelper.HexStringToByteArray(pubkey.ToHex()));
                    State.TokenContract.Transfer.Send(new TransferInput
                    {
                        To     = address,
                        Amount = amount,
                        Symbol = symbol
                    });
                }
            }
        }
示例#15
0
 public void Deserialize_Test()
 {
     var bytes = ByteArrayHelper.HexStringToByteArray(
         "0a200a1e9dee15619106b96861d52f03ad30ac7e57aa529eb2f05f7796472d8ce4a112200a1e96d8bf2dccf2ad419d02ed4a7b7a9d77df10617c4d731e766ce8dde63535320a496e697469616c697a653a0a0a015b120122180020005003");
     var    txBytes = ByteString.CopyFrom(bytes).ToByteArray();
     var    txn     = Transaction.Parser.ParseFrom(txBytes);
     string str     = txn.From.Value.ToByteArray().ToHex();
 }
示例#16
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 = ByteArrayHelper.HexStringToByteArray(rawTransactions[i]);
                    transaction = Transaction.Parser.ParseFrom(hexString);
                }
                catch
                {
                    throw new UserFriendlyException(Error.Message[Error.InvalidTransaction],
                                                    Error.InvalidTransaction.ToString());
                }

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

                var contractMethodDescriptor =
                    await GetContractMethodDescriptorAsync(transaction.To, transaction.MethodName);

                if (contractMethodDescriptor == null)
                {
                    throw new UserFriendlyException(Error.Message[Error.NoMatchMethodInContractAddress],
                                                    Error.NoMatchMethodInContractAddress.ToString());
                }

                var parameters = contractMethodDescriptor.InputType.Parser.ParseFrom(transaction.Params);

                if (!IsValidMessage(parameters))
                {
                    throw new UserFriendlyException(Error.Message[Error.InvalidParams], Error.InvalidParams.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);
        }
示例#17
0
 static SampleECKeyPairs()
 {
     KeyPairs = new ReadOnlyCollection <ECKeyPair>(
         _keys.Select(x =>
     {
         var privateKeyHex = x.Split(",").First();
         var privateKey    = ByteArrayHelper.HexStringToByteArray(privateKeyHex);
         return(CryptoHelper.FromPrivateKey(privateKey));
     }).ToList());
 }
        private Hash GetHashFromHexString(params string[] strings)
        {
            var hash = Hash.LoadFromByteArray(ByteArrayHelper.HexStringToByteArray(strings[0]));

            foreach (var s in strings.Skip(1))
            {
                hash = HashHelper.ComputeFrom(hash.ToByteArray().Concat(ByteArrayHelper.HexStringToByteArray(s)).ToArray());
            }

            return(hash);
        }
示例#19
0
        private (AEDPoSContractImplContainer.AEDPoSContractImplStub, BytesValue) ProperContractStub(MinerInRound minerInRound)
        {
            var pubkey  = ByteArrayHelper.HexStringToByteArray(minerInRound.Pubkey);
            var keyPair = SampleECKeyPairs.KeyPairs.First(p => p.PublicKey.BytesEqual(pubkey));

            _testDataProvider.SetKeyPair(keyPair);
            return(_contractTesterFactory.Create <AEDPoSContractImplContainer.AEDPoSContractImplStub>(
                       _consensusContractAddress, keyPair), new BytesValue {
                Value = ByteString.CopyFrom(pubkey)
            });
        }
示例#20
0
        public void Convert_Byte_FromString_Test()
        {
            var hexValue  = Hash.FromString("hexvalue").ToHex();
            var hashArray = ByteArrayHelper.HexStringToByteArray(hexValue);

            hashArray.Length.ShouldBe(32);

            var value       = "0x00";
            var valueArrary = ByteArrayHelper.HexStringToByteArray(value);

            valueArrary.Length.ShouldBe(1);
        }
        private (AEDPoSContractImplContainer.AEDPoSContractImplStub, BytesValue) ProperContractStub(
            MinerInRound minerInRound)
        {
            var pubkey  = ByteArrayHelper.HexStringToByteArray(minerInRound.Pubkey);
            var keyPair = SampleAccount.Accounts.First(a => a.KeyPair.PublicKey.BytesEqual(pubkey)).KeyPair;

            _testDataProvider.SetKeyPair(keyPair);
            Debug.WriteLine($"Chosen miner: {keyPair.PublicKey.ToHex()}");
            return(_contractTesterFactory.Create <AEDPoSContractImplContainer.AEDPoSContractImplStub>(
                       _consensusContractAddress, keyPair), new BytesValue {
                Value = ByteString.CopyFrom(pubkey)
            });
        }
        private void ShareInValueOfCurrentRound(Round currentRound, Round previousRound, Hash inValue, string publicKey)
        {
            if (!currentRound.RealTimeMinersInformation.ContainsKey(publicKey)) return;

            var minersCount = currentRound.RealTimeMinersInformation.Count;
            var minimumCount = minersCount.Mul(2).Div(3);
            minimumCount = minimumCount == 0 ? 1 : minimumCount;

            var secretShares = SecretSharingHelper.EncodeSecret(inValue.ToByteArray(), minimumCount, minersCount);
            foreach (var pair in currentRound.RealTimeMinersInformation.OrderBy(m => m.Value.Order)
                .ToDictionary(m => m.Key, m => m.Value.Order))
            {
                // Skip himself.
                if (pair.Key == publicKey) continue;

                var publicKeyOfAnotherMiner = pair.Key;
                var orderOfAnotherMiner = pair.Value;

                // Share in value of current round:

                // Encrypt every secret share with other miner's public key, then fill EncryptedInValues field.
                var plainMessage = secretShares[orderOfAnotherMiner - 1];
                var receiverPublicKey = ByteArrayHelper.HexStringToByteArray(publicKeyOfAnotherMiner);
                var encryptedInValue = Context.EncryptMessage(receiverPublicKey, plainMessage);
                currentRound.RealTimeMinersInformation[publicKey].EncryptedInValues
                    .Add(publicKeyOfAnotherMiner, ByteString.CopyFrom(encryptedInValue));

                // Decrypt shares published during previous round:

                // First round of every term don't have previous in values.
                if (IsFirstRoundOfCurrentTerm(out _)) continue;

                // Become a miner from this round.
                if (!previousRound.RealTimeMinersInformation.ContainsKey(publicKeyOfAnotherMiner)) continue;

                // No need to decrypt shares of miners who already revealed their previous in values.
                if (currentRound.RealTimeMinersInformation[publicKeyOfAnotherMiner].PreviousInValue != null) continue;

                var encryptedShares =
                    previousRound.RealTimeMinersInformation[publicKeyOfAnotherMiner].EncryptedInValues;
                if (!encryptedShares.Any()) continue;
                var interestingMessage = encryptedShares[publicKey];
                var senderPublicKey = ByteArrayHelper.HexStringToByteArray(publicKeyOfAnotherMiner);
                // Decrypt another miner's secret share then add a result to this miner's DecryptedInValues field.
                var decryptedInValue = Context.DecryptMessage(senderPublicKey, interestingMessage.ToByteArray());
                currentRound.RealTimeMinersInformation[publicKeyOfAnotherMiner].DecryptedPreviousInValues
                    .Add(publicKey, ByteString.CopyFrom(decryptedInValue));
            }
        }
        static SampleAccount()
        {
            Accounts = new ReadOnlyCollection <Account>(
                Keys.Select(x =>
            {
                var privateKeyHex = x.Split(",").First();
                var privateKey    = ByteArrayHelper.HexStringToByteArray(privateKeyHex);
                var keyPair       = CryptoHelper.FromPrivateKey(privateKey);

                return(new Account
                {
                    KeyPair = keyPair,
                    Address = Address.FromPublicKey(keyPair.PublicKey)
                });
            }).ToList());
        }
示例#24
0
        public async Task <string> ExecuteRawTransactionAsync(ExecuteRawTransactionDto input)
        {
            Transaction transaction;

            try
            {
                var byteArray = ByteArrayHelper.HexStringToByteArray(input.RawTransaction);
                transaction           = Transaction.Parser.ParseFrom(byteArray);
                transaction.Signature = ByteString.CopyFrom(ByteArrayHelper.HexStringToByteArray(input.Signature));
            }
            catch (Exception e)
            {
                Logger.LogError(e, e.Message); //for debug
                throw new UserFriendlyException(Error.Message[Error.InvalidParams],
                                                Error.InvalidParams.ToString());
            }

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

            try
            {
                var response = await CallReadOnlyAsync(transaction);

                try
                {
                    var contractMethodDescriptor =
                        await GetContractMethodDescriptorAsync(transaction.To, transaction.MethodName);

                    var output = contractMethodDescriptor.OutputType.Parser.ParseFrom(ByteString.CopyFrom(response));
                    return(JsonFormatter.ToDiagnosticString(output));
                }
                catch
                {
                    return(response?.ToHex());
                }
            }
            catch (Exception e)
            {
                throw new UserFriendlyException(Error.Message[Error.InvalidTransaction],
                                                Error.InvalidTransaction.ToString(), e.Message);
            }
        }
示例#25
0
        /// <summary>
        /// Update the candidate information,if it's not evil node.
        /// </summary>
        /// <param name="input">UpdateCandidateInformationInput</param>
        /// <returns></returns>
        public override Empty UpdateCandidateInformation(UpdateCandidateInformationInput input)
        {
            Assert(
                Context.GetContractAddressByName(SmartContractConstants.ConsensusContractSystemName) == Context.Sender,
                "Only consensus contract can update candidate information.");

            var candidateInformation = State.CandidateInformationMap[input.Pubkey];

            if (candidateInformation == null)
            {
                return(new Empty());
            }

            if (input.IsEvilNode)
            {
                var publicKeyByte = ByteArrayHelper.HexStringToByteArray(input.Pubkey);
                State.BlackList.Value.Value.Add(ByteString.CopyFrom(publicKeyByte));
                if (State.ProfitContract.Value == null)
                {
                    State.ProfitContract.Value =
                        Context.GetContractAddressByName(SmartContractConstants.ProfitContractSystemName);
                }
                State.ProfitContract.RemoveBeneficiary.Send(new RemoveBeneficiaryInput
                {
                    SchemeId    = State.SubsidyHash.Value,
                    Beneficiary = Address.FromPublicKey(publicKeyByte)
                });
                Context.LogDebug(() => $"Marked {input.Pubkey.Substring(0, 10)} as an evil node.");
                Context.Fire(new EvilMinerDetected {
                    Pubkey = input.Pubkey
                });
                State.CandidateInformationMap.Remove(input.Pubkey);
                var candidates = State.Candidates.Value;
                candidates.Value.Remove(ByteString.CopyFrom(publicKeyByte));
                State.Candidates.Value = candidates;
                return(new Empty());
            }

            candidateInformation.ProducedBlocks  = candidateInformation.ProducedBlocks.Add(input.RecentlyProducedBlocks);
            candidateInformation.MissedTimeSlots =
                candidateInformation.MissedTimeSlots.Add(input.RecentlyMissedTimeSlots);
            State.CandidateInformationMap[input.Pubkey] = candidateInformation;
            return(new Empty());
        }
        /// <summary>
        /// Remove current total shares of Votes Weight Reward,
        /// Add shares to current miners based on votes they obtained.
        /// </summary>
        /// <param name="previousTermInformation"></param>
        /// <param name="victories"></param>
        private void UpdateVotesWeightRewardWeights(Round previousTermInformation, IEnumerable <string> victories)
        {
            var previousMinerAddresses = previousTermInformation.RealTimeMinersInformation.Keys
                                         .Select(k => Address.FromPublicKey(ByteArrayHelper.HexStringToByteArray(k))).ToList();
            var votesWeightRewardProfitSubBeneficiaries = new RemoveBeneficiariesInput
            {
                SchemeId      = State.VotesWeightRewardHash.Value,
                Beneficiaries = { previousMinerAddresses }
            };

            State.ProfitContract.RemoveBeneficiaries.Send(votesWeightRewardProfitSubBeneficiaries);

            var votesWeightRewardProfitAddBeneficiaries = new AddBeneficiariesInput
            {
                SchemeId  = State.VotesWeightRewardHash.Value,
                EndPeriod = previousTermInformation.TermNumber.Add(1)
            };

            var dataCenterRankingList = State.ElectionContract.GetDataCenterRankingList.Call(new Empty());

            foreach (var victory in victories)
            {
                var obtainedVotes = 0L;
                if (dataCenterRankingList.DataCenters.ContainsKey(victory))
                {
                    obtainedVotes = dataCenterRankingList.DataCenters[victory];
                }

                var minerAddress = Address.FromPublicKey(ByteArrayHelper.HexStringToByteArray(victory));
                if (obtainedVotes > 0)
                {
                    votesWeightRewardProfitAddBeneficiaries.BeneficiaryShares.Add(new BeneficiaryShare
                    {
                        Beneficiary = minerAddress,
                        Shares      = obtainedVotes
                    });
                }
            }

            if (votesWeightRewardProfitAddBeneficiaries.BeneficiaryShares.Any())
            {
                State.ProfitContract.AddBeneficiaries.Send(votesWeightRewardProfitAddBeneficiaries);
            }
        }
示例#27
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)ByteArrayHelper.HexStringToByteArray("302010"));
            }

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

            if (typeof(T) == typeof(Address))
            {
                return((T)(object)SampleAddress.AddressList[0]);
            }

            throw new Exception("Not supported type.");
        }
 private void NotifyProfitReplaceCandidateInDataCenter(string oldCandidateInDataCenter,
                                                       string newCandidateDataCenter)
 {
     State.ProfitContract.RemoveBeneficiary.Send(new RemoveBeneficiaryInput
     {
         SchemeId    = State.SubsidyHash.Value,
         Beneficiary = Address.FromPublicKey(ByteArrayHelper.HexStringToByteArray(oldCandidateInDataCenter))
     });
     State.ProfitContract.AddBeneficiary.Send(new AddBeneficiaryInput
     {
         SchemeId         = State.SubsidyHash.Value,
         BeneficiaryShare = new BeneficiaryShare
         {
             Beneficiary =
                 Address.FromPublicKey(ByteArrayHelper.HexStringToByteArray(newCandidateDataCenter)),
             Shares = 1
         }
     });
 }
示例#29
0
        public void MultiMerge_Test()
        {
            var a = ByteArrayHelper.HexStringToByteArray(string.Concat(
                                                             "1000000000000000000000000000000000000000000000000000000000000000",
                                                             "1000000000000000000000000000000000000000000000000000000000000000",
                                                             "1000000000000000000000000000000000000000000000000000000000000000",
                                                             "1000000000000000000000000000000000000000000000000000000000000000",
                                                             "1000000000000000000000000000000000000000000000000000000000000000",
                                                             "1000000000000000000000000000000000000000000000000000000000000000",
                                                             "1000000000000000000000000000000000000000000000000000000000000000",
                                                             "1000000000000000000000000000000000000000000000000000000000000000"
                                                             ));

            var b = ByteArrayHelper.HexStringToByteArray(string.Concat(
                                                             "0100000000000000000000000000000000000000000000000000000000000000",
                                                             "0100000000000000000000000000000000000000000000000000000000000000",
                                                             "0100000000000000000000000000000000000000000000000000000000000000",
                                                             "0100000000000000000000000000000000000000000000000000000000000000",
                                                             "0100000000000000000000000000000000000000000000000000000000000000",
                                                             "0100000000000000000000000000000000000000000000000000000000000000",
                                                             "0100000000000000000000000000000000000000000000000000000000000000",
                                                             "0100000000000000000000000000000000000000000000000000000000000000"
                                                             ));

            var c = ByteArrayHelper.HexStringToByteArray(string.Concat(
                                                             "1100000000000000000000000000000000000000000000000000000000000000",
                                                             "1100000000000000000000000000000000000000000000000000000000000000",
                                                             "1100000000000000000000000000000000000000000000000000000000000000",
                                                             "1100000000000000000000000000000000000000000000000000000000000000",
                                                             "1100000000000000000000000000000000000000000000000000000000000000",
                                                             "1100000000000000000000000000000000000000000000000000000000000000",
                                                             "1100000000000000000000000000000000000000000000000000000000000000",
                                                             "1100000000000000000000000000000000000000000000000000000000000000"
                                                             ));

            var res = Bloom.AndMultipleBloomBytes(new List <byte[]>()
            {
                a, b
            });

            Assert.Equal(c, res);
        }
示例#30
0
        public void IsIn_Test()
        {
            var target = new Bloom(ByteArrayHelper.HexStringToByteArray(string.Concat(
                                                                            "1000000000000000000000000000000000000000000000000000000000000000",
                                                                            "1000000000000000000000000000000000000000000000000000000000000000",
                                                                            "1000000000000000000000000000000000000000000000000000000000000000",
                                                                            "1000000000000000000000000000000000000000000000000000000000000000",
                                                                            "1000000000000000000000000000000000000000000000000000000000000000",
                                                                            "1000000000000000000000000000000000000000000000000000000000000000",
                                                                            "1000000000000000000000000000000000000000000000000000000000000000",
                                                                            "1000000000000000000000000000000000000000000000000000000000000000"
                                                                            )));
            var source = new Bloom(ByteArrayHelper.HexStringToByteArray(string.Concat(
                                                                            "1000000000000000000000000000000000000000000000000000000000000000",
                                                                            "1000000000000000000000000000000000000000000000000000000000000000",
                                                                            "1000000000000000000000000000000000000000000000000000000000000000",
                                                                            "0000000000000000000000000000000000000000000000000000000000000000",
                                                                            "0000000000000000000000000000000000000000000000000000000000000000",
                                                                            "0000000000000000000000000000000000000000000000000000000000000000",
                                                                            "0000000000000000000000000000000000000000000000000000000000000000",
                                                                            "0000000000000000000000000000000000000000000000000000000000000000"
                                                                            )));

            Assert.True(source.IsIn(target));

            var wrongSource = new Bloom(ByteArrayHelper.HexStringToByteArray(string.Concat(
                                                                                 "1110000000000000000000000000000000000000000000000000000000000000",
                                                                                 "0000000000000000000000000000000000000000000000000000000000000000",
                                                                                 "0000000000000000000000000000000000000000000000000000000000000000",
                                                                                 "0000000000000000000000000000000000000000000000000000000000000000",
                                                                                 "0000000000000000000000000000000000000000000000000000000000000000",
                                                                                 "0000000000000000000000000000000000000000000000000000000000000000",
                                                                                 "0000000000000000000000000000000000000000000000000000000000000000",
                                                                                 "0000000000000000000000000000000000000000000000000000000000000000"
                                                                                 )));

            Assert.False(wrongSource.IsIn(target));

            var emptySource = new Bloom();

            Assert.False(emptySource.IsIn(target));
        }