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()
         }
     });
 }
示例#2
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ChunkSplit"/> class.
 /// </summary>
 /// <param name="data">The data to read from.</param>
 /// <param name="index">The index at which to start reading from.</param>
 internal ChunkSplit(byte[] data, int index)
 {
     _start1 = ChunkMarker.ConvertFromString(ByteArrayHelper.ToString(data, ref index));
     _end1   = ChunkMarker.ConvertFromString(ByteArrayHelper.ToString(data, ref index));
     _start2 = ChunkMarker.ConvertFromString(ByteArrayHelper.ToString(data, ref index));
     _end2   = ChunkMarker.ConvertFromString(ByteArrayHelper.ToString(data, ref index));
 }
        /// <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
                    })
                }
            });
        }
        /// <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;
        }
示例#5
0
        private static Id3Frame DecodeCustomUrlLink(byte[] data)
        {
            var frame = new CustomUrlLinkFrame {
                EncodingType = (Id3TextEncoding)data[0]
            };

            byte[][] splitBytes = ByteArrayHelper.SplitBySequence(data, 1, data.Length - 1,
                                                                  TextEncodingHelper.GetSplitterBytes(frame.EncodingType));
            string url = null;

            if (splitBytes.Length > 1)
            {
                frame.Description =
                    TextEncodingHelper.GetString(splitBytes[0], 0, splitBytes[0].Length, frame.EncodingType);
                url = TextEncodingHelper.GetDefaultString(splitBytes[1], 0, splitBytes[1].Length);
            }
            else if (splitBytes.Length == 1)
            {
                url = TextEncodingHelper.GetDefaultString(splitBytes[0], 0, splitBytes[0].Length);
            }

            frame.Url = url;

            return(frame);
        }
示例#6
0
        private static Id3Frame DecodePicture(byte[] data)
        {
            var frame = new PictureFrame {
                EncodingType = (Id3TextEncoding)data[0]
            };

            byte[] mimeType = ByteArrayHelper.GetBytesUptoSequence(data, 1, new byte[] { 0x00 });
            if (mimeType == null)
            {
                frame.MimeType = "image/";
                return(frame);
            }

            frame.MimeType = TextEncodingHelper.GetDefaultString(mimeType, 0, mimeType.Length);

            int currentPos = mimeType.Length + 2;

            frame.PictureType = (PictureType)data[currentPos];

            currentPos++;
            byte[] description = ByteArrayHelper.GetBytesUptoSequence(data, currentPos,
                                                                      TextEncodingHelper.GetSplitterBytes(frame.EncodingType));
            if (description == null)
            {
                return(frame);
            }
            frame.Description = TextEncodingHelper.GetString(description, 0, description.Length, frame.EncodingType);

            currentPos       += description.Length + TextEncodingHelper.GetSplitterBytes(frame.EncodingType).Length;
            frame.PictureData = new byte[data.Length - currentPos];
            Array.Copy(data, currentPos, frame.PictureData, 0, frame.PictureData.Length);

            return(frame);
        }
        public async Task ReadSubIfdReferencesAsync_ReadsCorrectly(ByteOrder byteOrder, TiffType type)
        {
            var stream = new StreamBuilder(byteOrder)
                         .WritePadding(20)
                         .WriteUInt32(10)
                         .WriteUInt32(42)
                         .WriteUInt32(30)
                         .ToStream();

            var tiffIfd = new TiffIfd
            {
                Entries = new[]
                {
                    new TiffIfdEntry {
                        Tag = 10, Type = TiffType.Ascii, Count = 10
                    },
                    new TiffIfdEntry {
                        Tag = TiffTags.SubIFDs, Type = type, Count = 3, Value = ByteArrayHelper.ToBytes(20u, byteOrder)
                    },
                    new TiffIfdEntry {
                        Tag = 20, Type = TiffType.Ascii, Count = 10
                    }
                }
            };

            var subIfdReferences = await TiffReader.ReadSubIfdReferencesAsync(tiffIfd, stream, byteOrder);

            Assert.Equal(new[] { new TiffIfdReference(10), new TiffIfdReference(42), new TiffIfdReference(30) }, subIfdReferences);
        }
示例#8
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
                    });
                }
            }
        }
示例#9
0
 /// <inheritdoc />
 protected override byte[] EncodeInternal()
 {
     return(ByteArrayHelper.Combine(
                ByteArrayHelper.ToBytes(_node.ConnectionName),
                ByteArrayHelper.ToBytes(_start.ToString()),
                ByteArrayHelper.ToBytes(_end.ToString())));
 }
示例#10
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);
        }
示例#11
0
        /// <inheritdoc cref="Command.ReportPhysicalAddress"/>
        /// <param name="source">The <c>CecMessage</c> source.</param>
        /// <param name="deviceType">Type of the device.</param>
        /// <param name="physicalAddress">The physical address.</param>
        /// <returns>A <c>CecMessage</c> that represents the command.</returns>
        public static CecMessage ReportPhysicalAddress(LogicalAddress source, DeviceType deviceType, PhysicalAddress physicalAddress)
        {
            var args = ByteArrayHelper.ToByteArray(physicalAddress.Address)
                       .Concat(ByteArrayHelper.ToByteArray(deviceType)).ToArray();

            return(new CecMessage(source, LogicalAddress.Unregistered, Command.ReportPhysicalAddress, args));
        }
示例#12
0
        /// <inheritdoc cref="Command.RoutingChange"/>
        /// <param name="source">The <c>CecMessage</c> source.</param>
        /// <param name="originalAddress">The original physical address.</param>
        /// <param name="newAddress">The new physical address.</param>
        /// <returns>A <c>CecMessage</c> that represents the command.</returns>
        public static CecMessage RoutingChange(LogicalAddress source, PhysicalAddress originalAddress, PhysicalAddress newAddress)
        {
            var parameters = ByteArrayHelper.ToByteArray(originalAddress.Address)
                             .Concat(ByteArrayHelper.ToByteArray(newAddress.Address)).ToArray();

            return(new CecMessage(source, LogicalAddress.Unregistered, Command.RoutingChange, parameters));
        }
示例#13
0
        /// <inheritdoc cref="Command.FeatureAbort"/>
        /// <param name="source">The <c>CecMessage</c> source.</param>
        /// <param name="destination">The <c>CecMessage</c> destination.</param>
        /// <param name="opCode">The <c>Command</c> which is aborted.</param>
        /// <param name="reason">A <c>AbortReason</c> value.</param>
        /// <returns>A <c>CecMessage</c> that represents the command.</returns>
        public static CecMessage FeatureAbort(LogicalAddress source, LogicalAddress destination, Command opCode, AbortReason reason)
        {
            var args = ByteArrayHelper.ToByteArray(opCode)
                       .Concat(ByteArrayHelper.ToByteArray(reason)).ToArray();

            return(new CecMessage(source, destination, Command.FeatureAbort, args));
        }
示例#14
0
        private ByteString GetSignatureWith(string privateKey, byte[] txData)
        {
            // Sign the hash
            var signature = CryptoHelper.SignWithPrivateKey(ByteArrayHelper.HexStringToByteArray(privateKey), txData);

            return(ByteString.CopyFrom(signature));
        }
        internal override byte[] GetPayload()
        {
            // Create the byte representation of the PSK
            byte[] pskData = SecurityType == SecurityType.WPA2 ? Encoding.UTF8.GetBytes(Psk) : new byte[0];

            /* Data format:
             *
             * - 00 [  1 ] Security type
             * - 01 [  1 ] SSID length
             * - 02 [  2 ] Reserved
             * - 04 [ 32 ] SSID
             * - 36 [  1 ] PSK length
             * - 37 [  3 ] Reserved
             * - 40 [ 64 ] PSK
             */

            byte[] payload = new byte[104];

            payload[0] = (byte)SecurityType;
            payload[1] = (byte)Ssid.Length;
            ByteArrayHelper.WriteBytes(Ssid, payload, 4);
            payload[36] = (byte)pskData.Length;
            ByteArrayHelper.WriteBytes(pskData, payload, 40);

            return(payload);
        }
示例#16
0
        public void Bytes_Equal_Test()
        {
            var byteArray1 = RandomFill(10);
            var byteArray2 = RandomFill(10);
            var byteArray3 = RandomFill(11);
            var result     = ByteArrayHelper.BytesEqual(byteArray1, byteArray2);

            result.ShouldBe(false);

            var result1 = ByteArrayHelper.BytesEqual(byteArray1, byteArray1);

            result1.ShouldBe(true);

            var result2 = ByteArrayHelper.BytesEqual(byteArray1, byteArray3);

            result2.ShouldBe(false);

            byte[] byteArray4 = new byte[10];
            for (int i = 0; i < 10; i++)
            {
                byteArray4[i] = byteArray1[i];
            }
            var result3 = byteArray1.BytesEqual(byteArray4);

            result3.ShouldBe(true);

            byte[] byteArray5 = null;
            var    result4    = byteArray5.BytesEqual(byteArray4);

            result4.ShouldBe(false);
        }
        /// <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());
        }
示例#18
0
        public void ToByteArrayTestFromByteString()
        {
            var value  = "01:09:32";
            var result = ByteArrayHelper.Parse(value);

            StringAssert.AreEqualIgnoringCase(value, result.ToHex());
        }
示例#19
0
        public void ToByteArrayTestFromBool()
        {
            var expected = "01";
            var result   = ByteArrayHelper.ToByteArray(true);

            Assert.AreEqual(expected, result.ToHex());
        }
示例#20
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);
        }
示例#21
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;
        }
示例#22
0
        public void Serialize_TestBool1_CheckLength()
        {
            var tbClass = new TestBool1();

            var ms = new MemoryStream();

            Serializer.Serialize(ms, tbClass);

            var b = ms.ToArray();

            Console.WriteLine($"b.Length {b.Length}");
            Console.WriteLine($"b {ByteArrayHelper.ByteArrayToString(b)}");
            //Assert.That(b.Length, Is.EqualTo(23));

            var tbClass2 = new TestBool1_Flags();

            ms = new MemoryStream();

            Serializer.Serialize(ms, tbClass2);

            b = ms.ToArray();

            Console.WriteLine($"b.Length {b.Length}");
            Console.WriteLine($"b {ByteArrayHelper.ByteArrayToString(b)}");
            //Assert.That(b.Length, Is.EqualTo(13));
        }
示例#23
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);
        }
示例#24
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);
            }
        }
示例#25
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);
        }
示例#26
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 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)));
        }
示例#28
0
        /// <summary>
        /// 解析元数据
        /// </summary>
        /// <param name="data">元数据</param>
        /// <returns>
        /// 返回能否解析的一个标示
        /// </returns>
        public override List <T> Parse <T>(byte[] data)
        {
            int      offset = 0;
            int      totalLength;
            List <T> messages = new List <T>();

            try
            {
                while (offset < data.Length)
                {
                    totalLength = BitConverter.ToInt32(data, offset);
                    if (totalLength > data.Length)
                    {
                        _tracing.Error("#Parse message failed, illegal total length. #length: " + totalLength);
                        return(messages);
                    }
                    byte[] messageData = totalLength == data.Length
                                             ? data
                                             : ByteArrayHelper.GetReallyData(data, offset, totalLength);
                    int  protocolId  = messageData[5];
                    int  serviceId   = messageData[6];
                    int  detailsId   = messageData[7];
                    Type messageType = GetMessageType(protocolId, serviceId, detailsId);
                    if (messageType == null)
                    {
                        _tracing.Error("#Parse message failed, illegal message protocol. #protocol id={0}, service id={1}, detalis id={2}\r\nTarget protocol stack: {3} ", protocolId, serviceId, detailsId, this);
                        return(messages);
                    }
                    offset += messageData.Length;
                    BaseMessage message;
                    try
                    {
                        //使用智能对象引擎进行解析
                        message = IntellectObjectEngine.GetObject <BaseMessage>(messageType, messageData);
                        if (message == null)
                        {
                            _tracing.Error("#Parse message failed, parse result = null. #protocol id={0}, service id={1}, detalis id={2}: ", protocolId, serviceId, detailsId);
                            return(messages);
                        }
                    }
                    catch (System.Exception ex)
                    {
                        _tracing.Error(ex, "#Parse message failed.");
                        continue;
                    }
                    messages.Add((T)(object)message);
                    if (data.Length - offset < 4)
                    {
                        break;
                    }
                }
                return(messages);
            }
            catch (System.Exception ex)
            {
                _tracing.Error(ex, "#Parse message failed.");
                return(messages);
            }
        }
示例#29
0
        public void ToByteArrayTestFromInt()
        {
            var expected = "01:09:32";
            var value    = 67890;
            var result   = ByteArrayHelper.ToByteArray(value, "X6");

            Assert.AreEqual(expected, result.ToHex());
        }
示例#30
0
        public void ToByteArrayTestFromByteEnum()
        {
            var value  = CecVersion.Version14;
            var result = ByteArrayHelper.ToByteArray(value);

            Assert.That(result.Length == 1);
            Assert.AreEqual((byte)value, result[0]);
        }