public Transaction CreateTransaction(string elementAt, string genesisAddress, string incrementid, string methodName, byte[] serializedParams, TransactionType contracttransaction) { try { Transaction t = new Transaction(); t.From = ByteArrayHelpers.FromHexString(elementAt); t.To = ByteArrayHelpers.FromHexString(genesisAddress); t.IncrementId = Convert.ToUInt64(incrementid); t.MethodName = methodName; t.Params = serializedParams; t.type = contracttransaction; _cmdInfo.Result = true; return(t); } catch (Exception e) { _cmdInfo.ErrorMsg.Add("Invalid transaction data: " + e.Message); return(null); } }
public string GetHeaderValue(ReadOnlySpan <byte> headerValue) { if (headerValue.Length == 0) { return(string.Empty); } // If it's a known header value, use the known value instead of allocating a new string. if (_knownHeader != null && _knownHeader.KnownValues != null) { string[] knownValues = _knownHeader.KnownValues; for (int i = 0; i < knownValues.Length; i++) { if (ByteArrayHelpers.EqualsOrdinalAsciiIgnoreCase(knownValues[i], headerValue)) { return(knownValues[i]); } } } return(HttpRuleParser.DefaultHttpEncoding.GetString(headerValue)); }
public void IsInTest() { var target = new Bloom(ByteArrayHelpers.FromHexString(string.Concat( "1000000000000000000000000000000000000000000000000000000000000000", "1000000000000000000000000000000000000000000000000000000000000000", "1000000000000000000000000000000000000000000000000000000000000000", "1000000000000000000000000000000000000000000000000000000000000000", "1000000000000000000000000000000000000000000000000000000000000000", "1000000000000000000000000000000000000000000000000000000000000000", "1000000000000000000000000000000000000000000000000000000000000000", "1000000000000000000000000000000000000000000000000000000000000000" ))); var source = new Bloom(ByteArrayHelpers.FromHexString(string.Concat( "1000000000000000000000000000000000000000000000000000000000000000", "1000000000000000000000000000000000000000000000000000000000000000", "1000000000000000000000000000000000000000000000000000000000000000", "0000000000000000000000000000000000000000000000000000000000000000", "0000000000000000000000000000000000000000000000000000000000000000", "0000000000000000000000000000000000000000000000000000000000000000", "0000000000000000000000000000000000000000000000000000000000000000", "0000000000000000000000000000000000000000000000000000000000000000" ))); Assert.True(source.IsIn(target)); var wrongSource = new Bloom(ByteArrayHelpers.FromHexString(string.Concat( "1110000000000000000000000000000000000000000000000000000000000000", "0000000000000000000000000000000000000000000000000000000000000000", "0000000000000000000000000000000000000000000000000000000000000000", "0000000000000000000000000000000000000000000000000000000000000000", "0000000000000000000000000000000000000000000000000000000000000000", "0000000000000000000000000000000000000000000000000000000000000000", "0000000000000000000000000000000000000000000000000000000000000000", "0000000000000000000000000000000000000000000000000000000000000000" ))); Assert.False(wrongSource.IsIn(target)); }
private static object ConvertType(object source, DataColumn column) { if (!(source is string)) { return(source); } var sourceAsString = (string)source; if (column.DataType == typeof(decimal)) { return(Convert.ChangeType(sourceAsString.Replace('.', ','), typeof(decimal))); } if (column.DataType == typeof(bool)) { return(sourceAsString.EqualsIgnoringCase("t")); } if (column.DataType == typeof(DateTime)) { DateTime dateTime; if (!TryParseDate(sourceAsString, out dateTime)) { const string messageFormat = "can't parse datetime from [{0}] for column [{1}]"; throw new InvalidOperationException(string.Format(messageFormat, source, column.ColumnName)); } return(dateTime < minSqlDate ? (object)null : dateTime); } if (column.DataType == typeof(byte[])) { if (string.IsNullOrEmpty(sourceAsString) || sourceAsString.Length < 2) { const string messageFormat = "can't parse byte array from [{0}] for column [{1}]"; throw new InvalidOperationException(string.Format(messageFormat, source, column.ColumnName)); } return(ByteArrayHelpers.FromHex(sourceAsString, 2)); } return(source); }
private async Task <Dictionary <string, string> > GetAndCreateAccountKey(DeployArg arg) { if (string.IsNullOrWhiteSpace(arg.ChainAccount)) { var keyStore = new AElfKeyStore(ApplicationHelper.AppDataPath); var chainPrefixBase58 = Base58CheckEncoding.Encode(ByteArrayHelpers.FromHexString(arg.SideChainId)); var chainPrefix = chainPrefixBase58.Substring(0, 4); var key = await keyStore.CreateAsync(arg.AccountPassword, chainPrefix); // todo clean //arg.ChainAccount = "ELF_" + chainPrefix + "_" + key.GetEncodedPublicKey(); } var fileName = arg.ChainAccount + ".ak"; var filePath = Path.Combine(ApplicationHelper.AppDataPath, "keys", fileName); var keyContent = File.ReadAllText(filePath); return(new Dictionary <string, string> { { fileName, keyContent } }); }
private void SetBpConfig() { var producers = MinersConfig.Instance.Producers; // Set the list of block producers try { foreach (var bp in producers.Values) { byte[] key = ByteArrayHelpers.FromHexString(bp["address"]); _bpAddresses.Add(key); } } catch (Exception e) { _logger?.Error(e, "Error while reading mining info."); } _nodeKey = NetworkConfig.Instance.EcKeyPair; // This nodes key _isBp = _bpAddresses.Any(k => k.BytesEqual(_nodeKey.GetAddress().DumpByteArray())); }
void IProtocolCodec.ClientEncode(CommDataBase data) { var client = (ModbusClient)data.OwnerProtocol; var command = (ModbusCommand)data.UserData; var fncode = command.FunctionCode; //encode the command body, if applies var body = new ByteArrayWriter(); var codec = CommandCodecs[fncode]; if (codec != null) { codec.ClientEncode(command, body); } //create a writer for the outgoing data var writer = new ByteArrayWriter(); //unit identifier (address) writer.WriteByte(client.Address); //function code writer.WriteByte(fncode); //body data writer.WriteBytes(body); //CRC-16 ushort crc = ByteArrayHelpers.CalcCRC16( writer.ToArray(), 0, writer.Length); writer.WriteInt16LE((short)crc); data.OutgoingData = writer.ToReader(); }
public void Init(ContainerBuilder builder) { var minerConfig = MinerConfig.Default; if (NodeConfig.Instance.IsMiner) { minerConfig = new MinerConfig { CoinBase = Address.LoadHex(NodeConfig.Instance.NodeAccount) }; } minerConfig.ChainId = new Hash() { Value = ByteString.CopyFrom(ByteArrayHelpers.FromHexString(ChainConfig.Instance.ChainId)) }; builder.RegisterModule(new MinerRpcAutofacModule()); builder.RegisterType <ClientManager>().SingleInstance().OnActivated(mc => { mc.Instance.Init(dir: ApplicationHelpers.GetDefaultConfigPath()); } ); builder.RegisterType <ServerManager>().SingleInstance().OnActivated(mc => { mc.Instance.Init(ApplicationHelpers.GetDefaultConfigPath()); } ); builder.RegisterModule(new MinerAutofacModule(minerConfig)); var txPoolConfig = TxPoolConfig.Default; txPoolConfig.FeeThreshold = 0; txPoolConfig.PoolLimitSize = TransactionPoolConfig.Instance.PoolLimitSize; txPoolConfig.Maximal = TransactionPoolConfig.Instance.Maximal; txPoolConfig.EcKeyPair = TransactionPoolConfig.Instance.EcKeyPair; builder.RegisterInstance(txPoolConfig).As <ITxPoolConfig>(); }
public static async Task <string[]> PublishTransactionsAsync(this ChainControllerRpcService s, string[] rawTransactions) { var txIds = new string[rawTransactions.Length]; var transactions = new List <Transaction>(); for (int i = 0; i < rawTransactions.Length; i++) { Transaction transaction; try { var hexString = ByteArrayHelpers.FromHexString(rawTransactions[i]); transaction = Transaction.Parser.ParseFrom(hexString); } catch { throw new JsonRpcServiceException(Error.InvalidTransaction, Error.Message[Error.InvalidTransaction]); } if (!transaction.VerifySignature()) { throw new JsonRpcServiceException(Error.InvalidTransaction, Error.Message[Error.InvalidTransaction]); } transactions.Add(transaction); txIds[i] = transaction.GetHash().ToHex(); } await s.LocalEventBus.PublishAsync(new TransactionsReceivedEvent() { Transactions = transactions }); return(txIds); }
public override void OnDeviceRegistersRead(string Name) { base.OnDeviceRegistersRead(Name); switch (Name) { case "PARAMS": _PARAMS_PREV = (UInt16[])_PARAMS.Clone(); CurrentParams = new NptParam_1KEX(); CurrentParams.ErrOut5 = ByteArrayHelpers.ReadSingle(_PARAMS, 0); CurrentParams.ErrOut4 = ByteArrayHelpers.ReadSingle(_PARAMS, 2); CurrentParams.ErrOut3 = ByteArrayHelpers.ReadSingle(_PARAMS, 4); CurrentParams.ErrOut2 = ByteArrayHelpers.ReadSingle(_PARAMS, 6); CurrentParams.ErrOut1 = ByteArrayHelpers.ReadSingle(_PARAMS, 8); CurrentParams.ErrOut0 = ByteArrayHelpers.ReadSingle(_PARAMS, 10); CurrentParams.ModeOut = _PARAMS[12]; CurrentParams.Ftime = ByteArrayHelpers.ReadSingle(_PARAMS, 13); CurrentParams.ModeTermRes = (byte)_PARAMS[20]; CurrentParams.ColdSold = _PARAMS[21] == 1; int sclass = _PARAMS[23], stype = _PARAMS[22]; CurrentParams.Sensor = AppManager.Worker.FindSensor(DEVTYPE, new SensorUID() { Class = sclass, Senstype = stype }); CurrentParams.MaxValue = ByteArrayHelpers.ReadSingle(_PARAMS, 15); CurrentParams.MinValue = ByteArrayHelpers.ReadSingle(_PARAMS, 17); CurrentParams.FuncSqrt = _PARAMS[19]; break; case "STATE": DeviceError = _STATE[4]; OutCurrent = ByteArrayHelpers.ReadSingle(_STATE, 5); Tempr = ByteArrayHelpers.ReadSingle(_STATE, 7); ShowDeviceError = DeviceError != 0 && DeviceError != 0x800; break; } }
public async Task <JObject> ProcessBroadcastTx(string raw64) { var hexString = ByteArrayHelpers.FromHexString(raw64); var transaction = Transaction.Parser.ParseFrom(hexString); var res = new JObject { ["hash"] = transaction.GetHash().DumpHex() }; if (!_canBroadcastTxs) { res["error"] = "Sync still in progress, cannot send transactions."; return(await Task.FromResult(res)); } // try // { // TODO: Wait validation done await TxHub.AddTransactionAsync(transaction); // if (valRes == TxValidation.TxInsertionAndBroadcastingError.Success) // { // MessageHub.Instance.Publish(new TransactionAddedToPool(transaction)); // } // else // { // res["error"] = valRes.ToString(); // } // } // catch (Exception e) // { // res["error"] = e.ToString(); // } return(await Task.FromResult(res)); }
GenerateConsensusInitializationCallList() { var consensusMethodCallList = new SystemContractDeploymentInput.Types.SystemTransactionMethodCallList(); consensusMethodCallList.Add(nameof(AEDPoSContract.InitialAElfConsensusContract), new InitialAElfConsensusContractInput { ElectionContractSystemName = ElectionSmartContractAddressNameProvider.Name, VoteContractSystemName = VoteSmartContractAddressNameProvider.Name, TokenContractSystemName = TokenSmartContractAddressNameProvider.Name, TimeEachTerm = int.MaxValue }); consensusMethodCallList.Add(nameof(AEDPoSContract.FirstRound), new Miners { PublicKeys = { _consensusOptions.InitialMiners.Select(p => ByteString.CopyFrom(ByteArrayHelpers.FromHexString(p))) } }.GenerateFirstRoundOfNewTerm(_consensusOptions.MiningInterval, _consensusOptions.StartTimestamp.ToUniversalTime())); return(consensusMethodCallList); }
/// <summary> /// Transfer dividends to miners. /// </summary> /// <param name="input"></param> /// <returns></returns> // ReSharper disable once InconsistentNaming public override SInt64Value TransferDividends(VotingRecord input) { var votingRecord = input; if (State.ConsensusContract.Value == null) { State.ConsensusContract.Value = State.BasicContractZero.GetContractAddressByName.Call(State.ConsensusContractSystemName.Value); } Assert(Context.Sender == State.ConsensusContract.Value, "Only consensus contract can transfer dividends."); var dividendsOwner = votingRecord.From; var dividendsOwnerAddress = Address.FromPublicKey(ByteArrayHelpers.FromHexString(dividendsOwner)); var startTermNumber = votingRecord.TermNumber + 1; var history = State.LastRequestedDividendsMap[votingRecord.TransactionId]; if (history > 0) { startTermNumber = history + 1; } var voteInfo = new VoteInfo() { Record = votingRecord, Age = State.ConsensusContract.GetBlockchainAge.Call(new Empty()).Value }; var endTermNumber = Math.Min(GetExpireTermNumber(voteInfo).Value, State.ConsensusContract.GetCurrentTermNumber.Call(new Empty()).Value - 1); // Record last requested dividends term number. var actualTermNumber = startTermNumber; long totalDividendsAmount = 0; for (var i = startTermNumber; i <= endTermNumber; i++) { var totalWeights = State.TotalWeightsMap[i]; Assert(totalWeights > 0, $"Total weights of term {i} not found."); var dividends = State.DividendsMap[i]; Assert(dividends > 0, $"Dividends of term {i} not found."); totalDividendsAmount += dividends * votingRecord.Weight / totalWeights; actualTermNumber = i; } if (State.TokenContract.Value == null) { State.TokenContract.Value = State.BasicContractZero.GetContractAddressByName.Call(State.TokenContractSystemName.Value); } State.TokenContract.Transfer.Send(new TransferInput { To = dividendsOwnerAddress, Amount = totalDividendsAmount, Symbol = Context.Variables.NativeSymbol, Memo = "Transfer dividends." }); Context.LogDebug(() => $"Gonna transfer {totalDividendsAmount} dividends to {dividendsOwnerAddress}"); State.LastRequestedDividendsMap[votingRecord.TransactionId] = actualTermNumber; return(new SInt64Value() { Value = totalDividendsAmount }); }
public async Task SendRawTransactionTest() { const string methodName = "Transfer"; var contractAddress = _smartContractAddressService.GetAddressByContractName(TokenSmartContractAddressNameProvider.Name); var chain = await _blockchainService.GetChainAsync(); var newUserKeyPair = CryptoHelpers.GenerateKeyPair(); var accountAddress = await _accountService.GetAccountAsync(); var toAddress = Base64.ToBase64String(Address.FromPublicKey(newUserKeyPair.PublicKey).Value.ToByteArray()); var parameters = new Dictionary <string, string> { { "From", accountAddress.GetFormatted() }, { "To", contractAddress.GetFormatted() }, { "RefBlockNumber", chain.BestChainHeight.ToString() }, { "RefBlockHash", chain.BestChainHash.ToHex() }, { "MethodName", methodName }, { "Params", "{\"to\":{ \"Value\": \"" + toAddress + "\" },\"symbol\":\"ELF\",\"amount\":100,\"memo\":\"test\"}" } }; var createTransactionResponse = await PostResponseAsObjectAsync <CreateRawTransactionOutput>( "/api/blockChain/rawTransaction", parameters, useApplicationJson : true); var transactionHash = Hash.FromRawBytes(ByteArrayHelpers.FromHexString(createTransactionResponse.RawTransaction)); var signature = await _accountService.SignAsync(transactionHash.DumpByteArray()); parameters = new Dictionary <string, string> { { "Transaction", createTransactionResponse.RawTransaction }, { "Signature", signature.ToHex() } }; var sendTransactionResponse = await PostResponseAsObjectAsync <SendRawTransactionOutput>( "/api/blockChain/sendRawTransaction", parameters, useApplicationJson : true); sendTransactionResponse.TransactionId.ShouldBe(transactionHash.ToHex()); sendTransactionResponse.Transaction.ShouldBeNull(); var existTransaction = await _txHub.GetExecutableTransactionSetAsync(); existTransaction.Transactions[0].GetHash().ToHex().ShouldBe(sendTransactionResponse.TransactionId); parameters = new Dictionary <string, string> { { "Transaction", createTransactionResponse.RawTransaction }, { "Signature", signature.ToHex() }, { "returnTransaction", "true" } }; sendTransactionResponse = await PostResponseAsObjectAsync <SendRawTransactionOutput>( "/api/blockChain/sendRawTransaction", parameters, useApplicationJson : true); sendTransactionResponse.TransactionId.ShouldBe(transactionHash.ToHex()); sendTransactionResponse.Transaction.ShouldNotBeNull(); sendTransactionResponse.Transaction.To.ShouldBe(contractAddress.GetFormatted()); sendTransactionResponse.Transaction.From.ShouldBe(accountAddress.GetFormatted()); sendTransactionResponse.Transaction.MethodName.ShouldBe(methodName); sendTransactionResponse.Transaction.Params.ShouldBe( "{ \"to\": \"" + Address.FromPublicKey(newUserKeyPair.PublicKey).GetFormatted() + "\", \"symbol\": \"ELF\", \"amount\": \"100\", \"memo\": \"test\" }"); sendTransactionResponse.Transaction.RefBlockNumber.ShouldBe(chain.BestChainHeight); sendTransactionResponse.Transaction.RefBlockPrefix.ShouldBe(ByteString.CopyFrom(chain.BestChainHash.Value.Take(4).ToArray()).ToBase64()); sendTransactionResponse.Transaction.Signature.ShouldBe(ByteString.CopyFrom(signature).ToBase64()); existTransaction = await _txHub.GetExecutableTransactionSetAsync(); existTransaction.Transactions[0].GetHash().ToHex().ShouldBe(sendTransactionResponse.TransactionId); }
/// <summary> /// Add PKCS#7 padding. This changes the array's length. /// </summary> public static byte[] Pkcs7(byte[] raw, int blocksize = 16) { return(ByteArrayHelpers.ForcePadWith(raw, blocksize, (byte)(blocksize - raw.Length % blocksize))); }
/// <summary> /// Remove PKCS#7 padding. This changes the array's length. /// </summary> public static byte[] UnPkcs7(byte[] raw) { int paddingLength = GetPkcs7Length(raw); return(ByteArrayHelpers.CopyPartOf(raw, 0, raw.Length - paddingLength)); }
private void ProcessCommand(CmdParseResult parsedCmd, CliCommandDefinition def) { string error = def.Validate(parsedCmd); if (!string.IsNullOrEmpty(error)) { _screenManager.PrintError(error); } else { if (def is GetDeserializedResultCmd g) { try { var str = g.Validate(parsedCmd); if (str != null) { _screenManager.PrintError(str); return; } // RPC var t = parsedCmd.Args.ElementAt(0); var data = parsedCmd.Args.ElementAt(1); byte[] sd; try { sd = ByteArrayHelpers.FromHexString(data); } catch (Exception e) { _screenManager.PrintError("Wrong data formant."); return; } object dd; try { dd = Deserializer.Deserialize(t, sd); } catch (Exception e) { _screenManager.PrintError("Invalid data format"); return; } if (dd == null) { _screenManager.PrintError("Not supported type."); return; } _screenManager.PrintLine(dd.ToString()); return; } catch (Exception e) { Console.WriteLine(e); return; } } if (def is LoadContractAbiCmd l) { error = l.Validate(parsedCmd); if (!string.IsNullOrEmpty(error)) { _screenManager.PrintError(error); } try { // RPC HttpRequestor reqhttp = new HttpRequestor(_rpcAddress); if (!parsedCmd.Args.Any()) { if (_genesisAddress == null) { _screenManager.PrintError(ConnectionNeeded); return; } parsedCmd.Args.Add(_genesisAddress); //parsedCmd.Args.Add(Globals.GenesisBasicContract); } var addr = parsedCmd.Args.ElementAt(0); Module m = null; if (!_loadedModules.TryGetValue(addr, out m)) { string resp = reqhttp.DoRequest(def.BuildRequest(parsedCmd).ToString()); if (resp == null) { _screenManager.PrintError(ServerConnError); return; } if (resp.IsEmpty()) { _screenManager.PrintError(NoReplyContentError); 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(addr, m); } var obj = JObject.FromObject(m); _screenManager.PrintLine(obj.ToString()); } catch (Exception e) { if (e is JsonReaderException) { _screenManager.PrintError(WrongInputFormat); return; } return; } return; } if (def is DeployContractCommand dcc) { if (_genesisAddress == null) { _screenManager.PrintError(NotConnected); return; } try { string err = dcc.Validate(parsedCmd); if (!string.IsNullOrEmpty(err)) { _screenManager.PrintLine(err); return; } //string cat = parsedCmd.Args.ElementAt(0); string filename = parsedCmd.Args.ElementAt(0); // Read sc bytes SmartContractReader screader = new SmartContractReader(); byte[] sc = screader.Read(filename); string hex = sc.ToHex(); var name = GlobalConfig.GenesisBasicContract; Module m = _loadedModules.Values.FirstOrDefault(ld => ld.Name.Equals(name)); if (m == null) { _screenManager.PrintError(AbiNotLoaded); return; } Method meth = m.Methods.FirstOrDefault(mt => mt.Name.Equals(DeploySmartContract)); if (meth == null) { _screenManager.PrintError(MethodNotFound); return; } byte[] serializedParams = meth.SerializeParams(new List <string> { "1", hex }); Transaction t = new Transaction(); t = CreateTransaction(parsedCmd.Args.ElementAt(2), _genesisAddress, DeploySmartContract, serializedParams, TransactionType.ContractTransaction); t = t.AddBlockReference(_rpcAddress); MemoryStream ms = new MemoryStream(); Serializer.Serialize(ms, t); byte[] b = ms.ToArray(); byte[] toSig = SHA256.Create().ComputeHash(b); ECSigner signer = new ECSigner(); ECSignature signature; ECKeyPair kp = _accountManager.GetKeyPair(parsedCmd.Args.ElementAt(2)); if (kp == null) { throw new AccountLockedException(parsedCmd.Args.ElementAt(2)); } signature = signer.Sign(kp, toSig); // Update the signature t.Sig = new Signature { R = signature.R, S = signature.S, P = kp.PublicKey.Q.GetEncoded() }; var resp = SignAndSendTransaction(t); if (resp == null) { _screenManager.PrintError(ServerConnError); return; } if (resp.IsEmpty()) { _screenManager.PrintError(NoReplyContentError); return; } JObject jObj = JObject.Parse(resp); string toPrint = def.GetPrintString(JObject.FromObject(jObj["result"])); _screenManager.PrintLine(toPrint); return; } catch (Exception e) { if (e is ContractLoadedException || e is AccountLockedException) { _screenManager.PrintError(e.Message); return; } if (e is InvalidTransactionException) { _screenManager.PrintError(InvalidTransaction); return; } if (e is JsonReaderException) { _screenManager.PrintError(WrongInputFormat); return; } return; } } // Execute // 2 cases : RPC command, Local command (like account management) if (def.IsLocal) { if (def is SendTransactionCmd c) { try { JObject j = JObject.Parse(parsedCmd.Args.ElementAt(0)); Transaction tr; tr = ConvertFromJson(j); string hex = tr.To.Value.ToHex(); Module m = null; if (!_loadedModules.TryGetValue(hex.Replace("0x", ""), out m)) { if (!_loadedModules.TryGetValue("0x" + hex.Replace("0x", ""), out m)) { _screenManager.PrintError(AbiNotLoaded); return; } } Method method = m.Methods?.FirstOrDefault(mt => mt.Name.Equals(tr.MethodName)); if (method == null) { _screenManager.PrintError(MethodNotFound); return; } JArray p = j["params"] == null ? null : JArray.Parse(j["params"].ToString()); tr.Params = j["params"] == null ? null : method.SerializeParams(p.ToObject <string[]>()); tr.type = TransactionType.ContractTransaction; tr = tr.AddBlockReference(_rpcAddress); _accountManager.SignTransaction(tr); var resp = SignAndSendTransaction(tr); if (resp == null) { _screenManager.PrintError(ServerConnError); return; } if (resp.IsEmpty()) { _screenManager.PrintError(NoReplyContentError); return; } JObject jObj = JObject.Parse(resp); string toPrint = def.GetPrintString(JObject.FromObject(jObj["result"])); _screenManager.PrintLine(toPrint); } catch (Exception e) { if (e is AccountLockedException || e is InvalidTransactionException || e is InvalidInputException) { _screenManager.PrintError(e.Message); } if (e is JsonReaderException || e is FormatException) { _screenManager.PrintError(WrongInputFormat); return; } } } else if (def is CallReadOnlyCmd) { JObject j = JObject.Parse(parsedCmd.Args.ElementAt(0)); Transaction tr; tr = ConvertFromJson(j); string hex = tr.To.Value.ToHex(); Module m = null; if (!_loadedModules.TryGetValue(hex.Replace("0x", ""), out m)) { if (!_loadedModules.TryGetValue("0x" + hex.Replace("0x", ""), out m)) { _screenManager.PrintError(AbiNotLoaded); return; } } Method method = m.Methods?.FirstOrDefault(mt => mt.Name.Equals(tr.MethodName)); if (method == null) { _screenManager.PrintError(MethodNotFound); return; } JArray p = j["params"] == null ? null : JArray.Parse(j["params"].ToString()); tr.Params = j["params"] == null ? null : method.SerializeParams(p.ToObject <string[]>()); var resp = CallTransaction(tr); if (resp == null) { _screenManager.PrintError(ServerConnError); return; } if (resp.IsEmpty()) { _screenManager.PrintError(NoReplyContentError); return; } JObject jObj = JObject.Parse(resp); string toPrint = def.GetPrintString(JObject.FromObject(jObj["result"])); _screenManager.PrintLine(toPrint); } else if (def is AccountCmd) { _accountManager.ProcessCommand(parsedCmd); } else if (def is CertificateCmd) { _certificatManager.ProcCmd(parsedCmd); } } else { try { // RPC HttpRequestor reqhttp = new HttpRequestor(_rpcAddress); string resp = reqhttp.DoRequest(def.BuildRequest(parsedCmd).ToString(), def.GetUrl()); if (resp == null) { _screenManager.PrintError(ServerConnError); return; } if (resp.IsEmpty()) { _screenManager.PrintError(NoReplyContentError); return; } JObject jObj = JObject.Parse(resp); var j = jObj["result"]; if (j["error"] != null) { _screenManager.PrintLine(j["error"].ToString()); return; } if (j["result"]?["BasicContractZero"] != null) { _genesisAddress = j["result"]["BasicContractZero"].ToString(); } string toPrint = def.GetPrintString(JObject.FromObject(j)); _screenManager.PrintLine(toPrint); } catch (Exception e) { if (e is UriFormatException) { _screenManager.PrintError(UriFormatEroor); return; } if (e is JsonReaderException) { _screenManager.PrintError(WrongInputFormat); return; } } } } }
CommResponse IProtocolCodec.ServerDecode(CommDataBase data) { var server = (ModbusServer)data.OwnerProtocol; var incoming = data.IncomingData; //validate header first var length = incoming.Length; if (length < 4) { goto LabelUnknown; } //address var address = incoming.ReadByte(); if (address == server.Address) { //function code var fncode = incoming.ReadByte(); if (fncode < CommandCodecs.Length) { //create a new command var command = new ModbusCommand(fncode); data.UserData = command; command.QueryTotalLength = 6; //= addr + fn + offset + crc //get the command codec var codec = CommandCodecs[fncode]; //decode the command, where possible var body = new ByteArrayReader(incoming.ReadBytes(length - 4)); codec.ServerDecode(command, body); //calculate the CRC-16 over the received stream ushort crcCalc = ByteArrayHelpers.CalcCRC16( incoming.ToArray(), 0, command.QueryTotalLength - 2); //validate the CRC-16 var crcRead = ByteArrayHelpers.ReadInt16LE( ((IByteArray)incoming).Data, command.QueryTotalLength - 2); if (crcRead == (short)crcCalc) { return(new CommResponse( data, CommResponse.Ack)); } } } //exception return(new CommResponse( data, CommResponse.Ignore)); LabelUnknown: return(new CommResponse( data, CommResponse.Unknown)); }
/// <summary> /// Running thread handler /// </summary> private void Worker() { #if NET45 System.Diagnostics.Trace.WriteLine("start"); #elif MF_FRAMEWORK_VERSION_V4_1 || MF_FRAMEWORK_VERSION_V4_2 Microsoft.SPOT.Debug.Print("start"); #endif //start the local timer, which gets the session dying int counter = IdleTimeout; int grace = 0; //create a writer for the incoming data ByteArrayWriter writer = null; var buffer = new byte[CacheSize]; using (Timer timer = new Timer( _ => { counter--; if (--grace == 0) { writer = null; } }, state: null, dueTime: 1000, period: 1000)) { //loop until the host closes, or the timer expires while ( this.Port.IsOpen && this._closing == false && counter > 0) { //look for incoming data int length = this.Port.BytesToRead; if (length > 0) { grace = 2; if (length > CacheSize) { length = CacheSize; } //read the data from the physical port this.Port.Read( buffer, 0, length); //append the data to the writer if (writer == null) { writer = new ByteArrayWriter(); } writer.WriteBytes( buffer, 0, length); //try to decode the incoming data var data = new ServerCommData(this.Protocol); data.IncomingData = writer.ToReader(); #if NET45 //System.Diagnostics.Trace.WriteLine("RX: " + ByteArrayHelpers.ToHex(((IByteArray)data.IncomingData).Data)); #elif MF_FRAMEWORK_VERSION_V4_1 || MF_FRAMEWORK_VERSION_V4_2 Microsoft.SPOT.Debug.Print("RX: " + ByteArrayHelpers.ToHex(((IByteArray)data.IncomingData).Data)); #endif CommResponse result = this.Protocol .Codec .ServerDecode(data); if (result.Status == CommResponse.Ack) { //the command is recognized, so call the host back this.OnServeCommand(data); //encode the host data this.Protocol .Codec .ServerEncode(data, 0); //return the resulting data to the remote caller byte[] outgoing = ((IByteArray)data.OutgoingData).Data; if (this.Port.IsOpen) { this.Port.Write( outgoing, 0, outgoing.Length); } else { break; } //reset the timer counter = IdleTimeout; writer = null; } //else if (result.Status == CommResponse.Ignore) //{ // writer = null; //} } Thread.Sleep(0); } } #if NET45 System.Diagnostics.Trace.WriteLine("close"); #elif MF_FRAMEWORK_VERSION_V4_1 || MF_FRAMEWORK_VERSION_V4_2 Microsoft.SPOT.Debug.Print("close"); #endif //marks the server not running this.IsRunning = false; }
CommResponse IProtocolCodec.ClientDecode(CommDataBase data) { var client = (ModbusClient)data.OwnerProtocol; var command = (ModbusCommand)data.UserData; var incoming = data.IncomingData; var bodyLen = incoming.Length - 4; //validate address first if (bodyLen >= 0 && incoming.ReadByte() == client.Address) { //extract function code var fncode = incoming.ReadByte(); //extract the message body var body = new ByteArrayReader(incoming.ReadBytes(bodyLen)); //calculate the CRC-16 over the received stream ushort crc = ByteArrayHelpers.CalcCRC16( incoming.ToArray(), 0, incoming.Length - 2); //validate the CRC-16 short u = incoming.ReadInt16LE(); if (u == (short)crc) { //message looks consistent (although the body can be empty) if ((fncode & 0x7F) == command.FunctionCode) { if (fncode <= 0x7F) { // //encode the command body, if applies var codec = CommandCodecs[fncode]; if (codec != null) { codec.ClientDecode(command, body); } return(new CommResponse( data, CommResponse.Ack)); } else { //exception if (incoming.CanRead(1)) { command.ExceptionCode = incoming.ReadByte(); } return(new CommResponse( data, CommResponse.Critical)); } } } } return(new CommResponse( data, CommResponse.Unknown)); }
private void ShareAndRecoverInValue(Round round, Round previousRound, Hash inValue, string publicKey) { var minersCount = round.RealTimeMinersInformation.Count; var minimumCount = (int)(minersCount * 2d / 3); minimumCount = minimumCount == 0 ? 1 : minimumCount; var secretShares = SecretSharingHelper.EncodeSecret(inValue.ToHex(), minimumCount, minersCount); foreach (var pair in round.RealTimeMinersInformation.OrderBy(m => m.Value.Order)) { var currentPublicKey = pair.Key; if (currentPublicKey == publicKey) { continue; } // Encrypt every secret share with other miner's public key, then fill own EncryptedInValues field. var plainMessage = Encoding.UTF8.GetBytes(secretShares[pair.Value.Order - 1]); var receiverPublicKey = ByteArrayHelpers.FromHexString(currentPublicKey); var encryptedInValue = Context.EncryptMessage(receiverPublicKey, plainMessage); round.RealTimeMinersInformation[publicKey].EncryptedInValues .Add(currentPublicKey, ByteString.CopyFrom(encryptedInValue)); if (previousRound.RoundId == 0 || round.TermNumber != previousRound.TermNumber) { continue; } var encryptedInValues = previousRound.RealTimeMinersInformation[currentPublicKey].EncryptedInValues; if (encryptedInValues.Any()) { var interestingMessage = encryptedInValues[publicKey]; var senderPublicKey = ByteArrayHelpers.FromHexString(currentPublicKey); // Decrypt every miner's secret share then add a result to other miner's DecryptedInValues field. var decryptedInValue = Context.DecryptMessage(senderPublicKey, interestingMessage.ToByteArray()); round.RealTimeMinersInformation[pair.Key].DecryptedPreviousInValues .Add(publicKey, ByteString.CopyFrom(decryptedInValue)); } if (pair.Value.DecryptedPreviousInValues.Count < minimumCount) { continue; } Context.LogDebug(() => "Now it's enough to recover previous in values."); // Try to recover others' previous in value. var orders = pair.Value.DecryptedPreviousInValues.Select((t, i) => previousRound.RealTimeMinersInformation.Values .First(m => m.PublicKey == pair.Value.DecryptedPreviousInValues.Keys.ToList()[i]).Order) .ToList(); var previousInValue = Hash.LoadHex(SecretSharingHelper.DecodeSecret( pair.Value.DecryptedPreviousInValues.Values.ToList() .Select(s => Encoding.UTF8.GetString(s.ToByteArray())).ToList(), orders, minimumCount)); if (round.RealTimeMinersInformation[pair.Key].PreviousInValue != null && round.RealTimeMinersInformation[pair.Key].PreviousInValue != previousInValue) { Context.LogDebug(() => "Different previous in value."); } round.RealTimeMinersInformation[pair.Key].PreviousInValue = previousInValue; } }
public override void SetCalibCmd(ushort cmd, float param) { CurrentCalibCommand = cmd; ByteArrayHelpers.WriteSingle(ref _CALIB_CMD, 0, param); _CALIB_CMD[3] = cmd; }
/// <summary> /// Entry-point for submitting a query to the remote device /// </summary> /// <param name="data"></param> /// <returns></returns> public CommResponse Query(ClientCommData data) { lock (this.Port) { try { //set the proper parameters to the port this.Port.BaudRate = this.Setting.BaudRate; this.Port.Parity = this.Setting.Parity; this.Port.DataBits = this.Setting.DataBits; this.Port.StopBits = this.Setting.StopBits; this.Port.RtsEnable = this.Setting.RtsEnable; } catch (Exception ex) { return(new CommResponse( data, CommResponse.Critical, ex.Message)); } //convert the request data as an ordinary byte array byte[] outgoing = ((IByteArray)data.OutgoingData).Data; //create a writer for accumulate the incoming data var incoming = new ByteArrayWriter(); const int tempSize = 64; var temp = new byte[tempSize]; //retries loop for (int attempt = 0, retries = data.Retries; attempt < retries; attempt++) { try { //flush any residual content this.Port .DiscardInBuffer(); this.Port .DiscardOutBuffer(); #if NET45 System.Diagnostics.Trace.WriteLine("TX: " + ByteArrayHelpers.ToHex(outgoing)); #endif //phyiscal writing this.Port .Write(outgoing, 0, outgoing.Length); } catch (Exception ex) { return(new CommResponse( data, CommResponse.Critical, ex.Message)); } incoming.Drop(); //start the local timer bool timeoutExpired; int totalTimeout = this.Latency + data.Timeout; using (Timer timer = new Timer( _ => timeoutExpired = true, state: null, dueTime: totalTimeout, period: Timeout.Infinite)) { //reception loop, until a valid response or timeout timeoutExpired = false; while (timeoutExpired == false) { int length = this.Port.BytesToRead; if (length > 0) { if (length > tempSize) { length = tempSize; } try { //read the incoming data from the physical port this.Port .Read(temp, 0, length); } catch (Exception ex) { return(new CommResponse( data, CommResponse.Critical, ex.Message)); } //append data to the writer incoming.WriteBytes( temp, 0, length); //try to decode the stream data.IncomingData = incoming.ToReader(); #if NET45 System.Diagnostics.Trace.WriteLine("RX: " + ByteArrayHelpers.ToHex(incoming.ToByteArray())); #endif CommResponse result = data .OwnerProtocol .Codec .ClientDecode(data); //exit whether any concrete result: either good or bad if (result.Status == CommResponse.Ack) { return(result); } else if (result.Status == CommResponse.Critical) { return(result); } else if (result.Status != CommResponse.Unknown) { break; } } Thread.Sleep(0); //stop immediately if the host asked to abort //TODO } } //using (timer) } //for //no attempt was successful return(new CommResponse( data, CommResponse.Critical)); } //lock }
public async Task TestTryAddNewContract() { RunnerConfig.Instance.SdkDir = _mock.SdkDir; var runner = new SmartContractRunner(); var reg = new SmartContractRegistration { Category = 0, ContractBytes = ByteString.CopyFrom(_mock.ContractCode), ContractHash = Hash.FromRawBytes(_mock.ContractCode) }; var resC = runner.ExtractMetadata(typeof(TestContractC)); // Structure of the test data var groundTruthResC = new Dictionary <string, FunctionMetadataTemplate>( new[] // function metadata map for contract { new KeyValuePair <string, FunctionMetadataTemplate>( "${this}.Func0", // local function name new FunctionMetadataTemplate( // local function metadata new HashSet <string>(), // calling set of this function metadata new HashSet <Resource>(new[] // local resource set of this function metadata { new Resource("${this}.resource4", DataAccessMode.AccountSpecific) // resource of the local resource set }))), new KeyValuePair <string, FunctionMetadataTemplate>( "${this}.Func1", new FunctionMetadataTemplate( new HashSet <string>(), new HashSet <Resource>(new[] { new Resource("${this}.resource5", DataAccessMode.ReadOnlyAccountSharing) }))) }); var groundTruthTemplateC = new ContractMetadataTemplate(typeof(TestContractC).FullName, groundTruthResC, new Dictionary <string, Address>()); Assert.Equal(groundTruthTemplateC, resC, new ContractMetadataTemplateEqualityComparer()); var resB = runner.ExtractMetadata(typeof(TestContractB)); var groundTruthResB = new Dictionary <string, FunctionMetadataTemplate>(new[] { new KeyValuePair <string, FunctionMetadataTemplate>( "${this}.Func0", new FunctionMetadataTemplate( new HashSet <string>(new[] { "${ContractC}.Func1" }), new HashSet <Resource>(new[] { new Resource("${this}.resource2", DataAccessMode.AccountSpecific) }))), new KeyValuePair <string, FunctionMetadataTemplate>( "${this}.Func1", new FunctionMetadataTemplate( new HashSet <string>(), new HashSet <Resource>(new[] { new Resource("${this}.resource3", DataAccessMode.ReadOnlyAccountSharing) }))) }); var refB = new Dictionary <string, Address>(new [] { new KeyValuePair <string, Address>("ContractC", Address.FromRawBytes(ByteArrayHelpers.FromHexString("0x456745674567456745674567456745674567"))), }); var groundTruthTemplateB = new ContractMetadataTemplate(typeof(TestContractB).FullName, groundTruthResB, refB); Assert.Equal(groundTruthTemplateB, resB, new ContractMetadataTemplateEqualityComparer()); var resA = runner.ExtractMetadata(typeof(TestContractA)); var groundTruthResA = new Dictionary <string, FunctionMetadataTemplate>(new[] { new KeyValuePair <string, FunctionMetadataTemplate>( "${this}.Func0(int)", new FunctionMetadataTemplate( new HashSet <string>(), new HashSet <Resource>())), new KeyValuePair <string, FunctionMetadataTemplate>( "${this}.Func0", new FunctionMetadataTemplate( new HashSet <string>(new[] { "${this}.Func1" }), new HashSet <Resource>(new[] { new Resource("${this}.resource0", DataAccessMode.AccountSpecific) }))), new KeyValuePair <string, FunctionMetadataTemplate>( "${this}.Func1", new FunctionMetadataTemplate( new HashSet <string>(new[] { "${this}.Func2" }), new HashSet <Resource>(new[] { new Resource("${this}.resource1", DataAccessMode.ReadOnlyAccountSharing) }))), new KeyValuePair <string, FunctionMetadataTemplate>( "${this}.Func2", new FunctionMetadataTemplate( new HashSet <string>(), new HashSet <Resource>(new[] { new Resource("${this}.resource1", DataAccessMode.ReadOnlyAccountSharing), new Resource("${this}.resource2", DataAccessMode.ReadWriteAccountSharing) }))), new KeyValuePair <string, FunctionMetadataTemplate>( "${this}.Func3", new FunctionMetadataTemplate( new HashSet <string>(new[] { "${_contractB}.Func0", "${this}.Func0", "${ContractC}.Func0" }), new HashSet <Resource>(new[] { new Resource("${this}.resource1", DataAccessMode.ReadOnlyAccountSharing) }))), new KeyValuePair <string, FunctionMetadataTemplate>( "${this}.Func4", new FunctionMetadataTemplate( new HashSet <string>(new[] { "${this}.Func2", "${this}.Func2" }), new HashSet <Resource>())), new KeyValuePair <string, FunctionMetadataTemplate>( "${this}.Func5", new FunctionMetadataTemplate( new HashSet <string>(new[] { "${_contractB}.Func1", "${this}.Func3" }), new HashSet <Resource>())), }); var refA = new Dictionary <string, Address>(new [] { new KeyValuePair <string, Address>("ContractC", Address.FromRawBytes(ByteArrayHelpers.FromHexString("0x456745674567456745674567456745674567"))), new KeyValuePair <string, Address>("_contractB", Address.FromRawBytes(ByteArrayHelpers.FromHexString("0x123412341234123412341234123412341234"))), }); var groundTruthTemplateA = new ContractMetadataTemplate(typeof(TestContractA).FullName, groundTruthResA, refA); Assert.Equal(groundTruthTemplateA, resA, new ContractMetadataTemplateEqualityComparer()); //test fail cases await TestFailCases(runner); }
/// <summary> /// Reads the bytes from the stream. /// </summary> private async Task Read() { try { while (true) { // Read type int type = await ReadByte(); // Read if the message is associated with an id bool hasId = await ReadBoolean(); byte[] id = null; if (hasId) { // The Id is a 128-bit guid id = await ReadBytesAsync(IdLength); } // Is this a partial reception ? bool isBuffered = await ReadBoolean(); // Read the size of the data int length = await ReadInt(); if (isBuffered) { // If it's a partial packet read the packet info PartialPacket partialPacket = await ReadPartialPacket(length); // todo property control if (!partialPacket.IsEnd) { _partialPacketBuffer.Add(partialPacket); if (_partialPacketBuffer.Count == 0) { _logger.Trace($"Received first packet: {partialPacket.Type}, total size: {partialPacket.TotalDataSize}."); } } else { // This is the last packet // Concat all data _partialPacketBuffer.Add(partialPacket); byte[] allData = ByteArrayHelpers.Combine(_partialPacketBuffer.Select(pp => pp.Data).ToArray()); _logger.Trace($"Received last packet: {_partialPacketBuffer.Count}, total length: {allData.Length}."); // Clear the buffer for the next partial to receive _partialPacketBuffer.Clear(); Message message; if (hasId) { message = new Message { Type = type, HasId = true, Id = id, Length = allData.Length, Payload = allData }; } else { message = new Message { Type = type, HasId = false, Length = allData.Length, Payload = allData }; } FireMessageReceivedEvent(message); } } else { // If it's not a partial packet the next "length" bytes should be // the entire data byte[] packetData = await ReadBytesAsync(length); Message message; if (hasId) { message = new Message { Type = type, HasId = true, Id = id, Length = length, Payload = packetData }; } else { message = new Message { Type = type, HasId = false, Length = length, Payload = packetData }; } FireMessageReceivedEvent(message); } } } catch (PeerDisconnectedException) { StreamClosed?.Invoke(this, EventArgs.Empty); Close(); } catch (Exception e) { if (!IsConnected && e is IOException) { // If the stream fails while the connection is logically closed (call to Close()) // we simply return - the StreamClosed event will no be closed. return; } Close(); StreamClosed?.Invoke(this, EventArgs.Empty); } }
/// <summary> /// Create side chain. It is a proposal result from system address. /// </summary> /// <param name="input"></param> /// <returns></returns> public override SInt32Value CreateSideChain(SInt32Value input) { var chainId = input.Value; // side chain creation should be triggered by organization address from parliament. CheckOwnerAuthority(); var sideChainInfo = State.SideChainInfos[chainId]; Assert( sideChainInfo != null && sideChainInfo.SideChainStatus == SideChainStatus.Review, "Side chain creation request not found."); sideChainInfo.SideChainStatus = SideChainStatus.Active; sideChainInfo.CreatedTime = Timestamp.FromDateTime(Context.CurrentBlockTime); State.SideChainInfos[chainId] = sideChainInfo; State.CurrentSideChainHeight[chainId] = 0; var initialConsensusInfo = GetCurrentMiners(); State.SideChainInitialConsensusInfo[chainId] = new BytesValue { Value = initialConsensusInfo.ToByteString() }; Context.LogDebug(() => $"Initial miner list for side chain {chainId} :" + string.Join(",", initialConsensusInfo.MinerList.PublicKeys.Select(p => Address.FromPublicKey(ByteArrayHelpers.FromHexString(p)).ToString()))); Context.LogDebug(() => $"RoundNumber {initialConsensusInfo.RoundNumber}"); // Event is not used for now. Context.Fire(new CreationRequested() { ChainId = chainId, Creator = Context.Sender }); return(new SInt32Value() { Value = chainId }); }
protected override Task <byte[]> GetInternalEntropyAsync(EntropyPriority priority) { // This reads details of all network interfaces running on the system, and uses them as inputs to a hash for final result. // Given this isn't trivial work, we run in a separate threadpool task. return(Task.Run(() => { Log.Trace("Beginning to gather entropy."); var ins = NetworkInterface.GetAllNetworkInterfaces(); Log.Trace("Found {0:N0} interfaces.", ins.Length); // First result includes IP address, hardware address, etc. var allStats = new List <long>(); if (!_HasRunOnce) { Log.Trace("Including static properties on first run."); allStats.AddRange(GetNetworkInterfaceStaticProperties(ins)); _HasRunOnce = true; } // After that, its just the number of packets, etc. foreach (var i in ins) { // Most of these will be zero. // Note that these can throw on some platforms, so we do a bunch of exception wrapping. var stats = i.GetIPStatistics(); if (!_BytesReceivedFailed) { ExceptionHelper.TryAndIgnoreException(() => Uh.ToUnit(() => allStats.Add(stats.BytesReceived)), ref _BytesReceivedFailed); } if (!_BytesSentFailed) { ExceptionHelper.TryAndIgnoreException(() => Uh.ToUnit(() => allStats.Add(stats.BytesSent)), ref _BytesSentFailed); } if (!_IncomingPacketsDiscardedFailed) { ExceptionHelper.TryAndIgnoreException(() => Uh.ToUnit(() => allStats.Add(stats.IncomingPacketsDiscarded)), ref _IncomingPacketsDiscardedFailed); } if (!_IncomingPacketsWithErrorsFailed) { ExceptionHelper.TryAndIgnoreException(() => Uh.ToUnit(() => allStats.Add(stats.IncomingPacketsWithErrors)), ref _IncomingPacketsWithErrorsFailed); } if (!_IncomingUnknownProtocolPacketsFailed) { ExceptionHelper.TryAndIgnoreException(() => Uh.ToUnit(() => allStats.Add(stats.IncomingUnknownProtocolPackets)), ref _IncomingUnknownProtocolPacketsFailed); } if (!_NonUnicastPacketsReceivedFailed) { ExceptionHelper.TryAndIgnoreException(() => Uh.ToUnit(() => allStats.Add(stats.NonUnicastPacketsReceived)), ref _NonUnicastPacketsReceivedFailed); } if (!_NonUnicastPacketsSentFailed) { ExceptionHelper.TryAndIgnoreException(() => Uh.ToUnit(() => allStats.Add(stats.NonUnicastPacketsSent)), ref _NonUnicastPacketsSentFailed); } if (!_OutgoingPacketsDiscardedFailed) { ExceptionHelper.TryAndIgnoreException(() => Uh.ToUnit(() => allStats.Add(stats.OutgoingPacketsDiscarded)), ref _OutgoingPacketsDiscardedFailed); } if (!_OutgoingPacketsWithErrorsFailed) { ExceptionHelper.TryAndIgnoreException(() => Uh.ToUnit(() => allStats.Add(stats.OutgoingPacketsWithErrors)), ref _OutgoingPacketsWithErrorsFailed); } if (!_OutputQueueLengthFailed) { ExceptionHelper.TryAndIgnoreException(() => Uh.ToUnit(() => allStats.Add(stats.OutputQueueLength)), ref _OutputQueueLengthFailed); } if (!_UnicastPacketsReceivedFailed) { ExceptionHelper.TryAndIgnoreException(() => Uh.ToUnit(() => allStats.Add(stats.UnicastPacketsReceived)), ref _UnicastPacketsReceivedFailed); } if (!_UnicastPacketsSentFailed) { ExceptionHelper.TryAndIgnoreException(() => Uh.ToUnit(() => allStats.Add(stats.UnicastPacketsSent)), ref _UnicastPacketsSentFailed); } // Remaining lease duration. if (!_AddressValidLifetimeFailed) { ExceptionHelper.TryAndIgnoreException(() => Uh.ToUnit(() => { var props = i.GetIPProperties(); allStats.AddRange(props.UnicastAddresses.Select(x => x.AddressValidLifetime)); }), ref _AddressValidLifetimeFailed); } } // Remove zeros and shuffle to prevent obvious correlations. var statsNoZero = allStats.Where(x => x != 0L).ToArray(); Log.Trace("Read {0:N0} non-zero stat items.", statsNoZero.Length); if (LogRawStats) { Log.Trace("Raw stats: ", statsNoZero.LongsToHexString()); } // Shuffle the details, so there isn't a repetition of similar stats. statsNoZero.ShuffleInPlace(_Rng); // Convert to digest byte array to return. var result = ByteArrayHelpers.LongsToDigestBytes(statsNoZero, _ItemsPerResultChunk); Log.Trace("Converted stats to {0:N0} bytes of entropy.", result.Length); return result; })); }
public void AddHashAddValueTest() { var empty = BytesValue.Parser.ParseFrom(ByteString.Empty); var elf = new StringValue() { Value = "ELF" }; // Serialized: 0a03454c46 // sha256 of empty string: e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 // sha256 of 0a03454c46: 782330156f8c9403758ed30270a3e2d59e50b8f04c6779d819b72eee02addb13 var expected = string.Concat( "0000000000000000000000000000100000000000000000000000000000000000", "0000000000000000000000000000000000000000000000000000000000000000", "0000000000000000000000000000000000000000000000000000000000000000", "0000000000000000000000000000000000000000000000040000000000000000", "0000000000000000000100000000000000000000000000000000000000000000", "0000000000000000000000000000000000000000000000000000000000000000", "0000000000000000000000000000000000000000000000000000000000000000", "1000000000000000000000000000000000000000000000000000000800200000" ); var bloom = new Bloom(); bloom.AddSha256Hash( ByteArrayHelpers.FromHexString("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")); bloom.AddSha256Hash( ByteArrayHelpers.FromHexString("782330156f8c9403758ed30270a3e2d59e50b8f04c6779d819b72eee02addb13")); Assert.Equal(expected, bloom.Data.ToHex().Replace("0x", "")); // add value var bloom1 = new Bloom(); bloom1.AddValue(empty); bloom1.AddValue(elf); Assert.Equal(expected, bloom1.Data.ToHex().Replace("0x", "")); // Take only 12 characters (2 * 3 = 6 bytes) var bloom2 = new Bloom(); var fiftyTwoZeros = string.Join("", Enumerable.Repeat("0", 52)); // Too short Assert.ThrowsAny <Exception>(() => bloom2.AddSha256Hash(ByteArrayHelpers.FromHexString("e3b0c44298fc"))); Assert.ThrowsAny <Exception>(() => bloom2.AddSha256Hash(ByteArrayHelpers.FromHexString("782330156f8c"))); // Too long Assert.ThrowsAny <Exception>(() => bloom2.AddSha256Hash(ByteArrayHelpers.FromHexString("e3b0c44298fc" + "00" + fiftyTwoZeros))); Assert.ThrowsAny <Exception>(() => bloom2.AddSha256Hash(ByteArrayHelpers.FromHexString("782330156f8c" + "00" + fiftyTwoZeros))); // Right size bloom2.AddSha256Hash(ByteArrayHelpers.FromHexString("e3b0c44298fc" + fiftyTwoZeros)); bloom2.AddSha256Hash(ByteArrayHelpers.FromHexString("782330156f8c" + fiftyTwoZeros)); Assert.Equal(expected, bloom2.Data.ToHex().Replace("0x", "")); // Incorrect value var bloom3 = new Bloom(); bloom3.AddSha256Hash(ByteArrayHelpers.FromHexString("e3b0c44298f0" + fiftyTwoZeros)); bloom3.AddSha256Hash(ByteArrayHelpers.FromHexString("782330156f80" + fiftyTwoZeros)); Assert.NotEqual(expected, bloom3.Data.ToHex().Replace("0x", "")); }
private List <Address> GetRepresentatives() { ValidateConsensusContract(); var miner = State.ConsensusContract.GetCurrentMiners.Call(new Empty()); var representatives = miner.MinerList.PublicKeys.Select(publicKey => Address.FromPublicKey(ByteArrayHelpers.FromHexString(publicKey))).ToList(); return(representatives); }
private Hash CreateLeafFromHex(string hex) { return(Hash.LoadByteArray(ByteArrayHelpers.FromHexString(hex))); }