public BlockHeader Decode(Rlp.DecoderContext context, RlpBehaviors rlpBehaviors = RlpBehaviors.None) { if (context.IsNextItemNull()) { return(null); } var headerRlp = context.PeekNextItem(); int headerSequenceLength = context.ReadSequenceLength(); int headerCheck = context.Position + headerSequenceLength; Keccak parentHash = context.DecodeKeccak(); Keccak ommersHash = context.DecodeKeccak(); Address beneficiary = context.DecodeAddress(); Keccak stateRoot = context.DecodeKeccak(); Keccak transactionsRoot = context.DecodeKeccak(); Keccak receiptsRoot = context.DecodeKeccak(); Bloom bloom = context.DecodeBloom(); UInt256 difficulty = context.DecodeUInt256(); UInt256 number = context.DecodeUInt256(); UInt256 gasLimit = context.DecodeUInt256(); UInt256 gasUsed = context.DecodeUInt256(); UInt256 timestamp = context.DecodeUInt256(); byte[] extraData = context.DecodeByteArray(); Keccak mixHash = context.DecodeKeccak(); BigInteger nonce = context.DecodeUBigInt(); if (!rlpBehaviors.HasFlag(RlpBehaviors.AllowExtraData)) { context.Check(headerCheck); } BlockHeader blockHeader = new BlockHeader( parentHash, ommersHash, beneficiary, difficulty, (long)number, (long)gasLimit, timestamp, extraData); blockHeader.StateRoot = stateRoot; blockHeader.TransactionsRoot = transactionsRoot; blockHeader.ReceiptsRoot = receiptsRoot; blockHeader.Bloom = bloom; blockHeader.GasUsed = (long)gasUsed; blockHeader.MixHash = mixHash; blockHeader.Nonce = (ulong)nonce; blockHeader.Hash = Keccak.Compute(headerRlp); return(blockHeader); }
private void SetSecrets(EncryptionHandshake handshake, HandshakeRole handshakeRole) { byte[] ephemeralSharedSecret = BouncyCrypto.Agree(handshake.EphemeralPrivateKey, handshake.RemoteEphemeralPublicKey); byte[] nonceHash = Keccak.Compute(Bytes.Concat(handshake.RecipientNonce, handshake.InitiatorNonce)).Bytes; byte[] sharedSecret = Keccak.Compute(Bytes.Concat(ephemeralSharedSecret, nonceHash)).Bytes; byte[] token = Keccak.Compute(sharedSecret).Bytes; byte[] aesSecret = Keccak.Compute(Bytes.Concat(ephemeralSharedSecret, sharedSecret)).Bytes; Array.Clear(sharedSecret, 0, sharedSecret.Length); // TODO: it was passed in the concat for Keccak so not good enough byte[] macSecret = Keccak.Compute(Bytes.Concat(ephemeralSharedSecret, aesSecret)).Bytes; Array.Clear(ephemeralSharedSecret, 0, ephemeralSharedSecret.Length); // TODO: it was passed in the concat for Keccak so not good enough handshake.Secrets = new EncryptionSecrets(); handshake.Secrets.Token = token; handshake.Secrets.AesSecret = aesSecret; handshake.Secrets.MacSecret = macSecret; KeccakDigest mac1 = new KeccakDigest(MacBitsSize); mac1.BlockUpdate(macSecret.Xor(handshake.RecipientNonce), 0, macSecret.Length); mac1.BlockUpdate(handshake.AuthPacket.Data, 0, handshake.AuthPacket.Data.Length); KeccakDigest mac2 = new KeccakDigest(MacBitsSize); mac2.BlockUpdate(macSecret.Xor(handshake.InitiatorNonce), 0, macSecret.Length); mac2.BlockUpdate(handshake.AckPacket.Data, 0, handshake.AckPacket.Data.Length); if (handshakeRole == HandshakeRole.Initiator) { handshake.Secrets.EgressMac = mac1; handshake.Secrets.IngressMac = mac2; } else { handshake.Secrets.EgressMac = mac2; handshake.Secrets.IngressMac = mac1; } if (_logger.IsTrace) { _logger.Trace($"Agreed secrets with {handshake.RemoteNodeId}"); } #if DEBUG if (_logger.IsTrace) { _logger.Trace($"{handshake.RemoteNodeId} ephemeral private key {handshake.EphemeralPrivateKey}"); _logger.Trace($"{handshake.RemoteNodeId} initiator nonce {handshake.InitiatorNonce.ToHexString()}"); _logger.Trace($"{handshake.RemoteNodeId} recipient nonce {handshake.RecipientNonce.ToHexString()}"); _logger.Trace($"{handshake.RemoteNodeId} remote ephemeral public key {handshake.RemoteEphemeralPublicKey}"); _logger.Trace($"{handshake.RemoteNodeId} remote public key {handshake.RemoteNodeId}"); _logger.Trace($"{handshake.RemoteNodeId} auth packet {handshake.AuthPacket.Data.ToHexString()}"); _logger.Trace($"{handshake.RemoteNodeId} ack packet {handshake.AckPacket.Data.ToHexString()}"); } #endif }
public void Equals_works() { Address addressA = new Address(Keccak.Compute("a")); Address addressA2 = new Address(Keccak.Compute("a")); Address addressB = new Address(Keccak.Compute("b")); Assert.True(addressA.Equals(addressA2)); // ReSharper disable once EqualExpressionComparison Assert.True(addressA.Equals(addressA)); Assert.False(addressA.Equals(addressB)); Assert.False(addressA.Equals(null)); }
public async Task Can_make_and_verify_deposit_locally() { DepositService depositService = new DepositService(_ndmBridge, _abiEncoder, _wallet, _contractAddress); Deposit deposit = new Deposit(Keccak.Compute("a secret"), 10, (uint)Timestamper.Default.EpochSeconds + 86000, 1.Ether()); Keccak depositTxHash = await depositService.MakeDepositAsync(_consumerAccount, deposit, 20.GWei()); _bridge.IncrementNonce(_consumerAccount); TxReceipt depositTxReceipt = _bridge.GetReceipt(depositTxHash); Assert.AreEqual(StatusCode.Success, depositTxReceipt.StatusCode, $"deposit made {depositTxReceipt.Error} {Encoding.UTF8.GetString(depositTxReceipt.ReturnValue ?? new byte[0])}"); Assert.True(await depositService.VerifyDepositAsync(_consumerAccount, deposit.Id) > 0, "deposit verified"); }
public void GlobalSetup() { _scenarios = new[] { Nethermind.Core.Encoding.Rlp.Encode(Keccak.Zero).Bytes, Nethermind.Core.Encoding.Rlp.Encode(Keccak.EmptyTreeHash).Bytes, Nethermind.Core.Encoding.Rlp.Encode(Keccak.OfAnEmptyString).Bytes, Nethermind.Core.Encoding.Rlp.Encode(Keccak.OfAnEmptySequenceRlp).Bytes, Nethermind.Core.Encoding.Rlp.Encode(Keccak.OfAnEmptyString).Bytes.Concat(new byte[100000]).ToArray(), Nethermind.Core.Encoding.Rlp.Encode(Keccak.Compute("a")).Bytes.Concat(new byte[100000]).ToArray() }; }
public async Task Returns_a_valid_balance() { DepositService depositService = new DepositService(_ndmBridge, _abiEncoder, _wallet, _contractAddress); Deposit deposit = new Deposit(Keccak.Compute("a secret"), 10, (uint)Timestamper.Default.EpochSeconds + 86000, 1.Ether()); Keccak depositTxHash = await depositService.MakeDepositAsync(_consumerAccount, deposit, 20.GWei()); _bridge.IncrementNonce(_consumerAccount); TxReceipt depositTxReceipt = _bridge.GetReceipt(depositTxHash); UInt256 balance = await depositService.ReadDepositBalanceAsync(_consumerAccount, deposit.Id); Assert.AreEqual(balance, 1.Ether()); }
public void GlobalSetup() { _scenarios = new[] { Serialization.Rlp.Rlp.Encode(Keccak.Zero).Bytes, Serialization.Rlp.Rlp.Encode(Keccak.EmptyTreeHash).Bytes, Serialization.Rlp.Rlp.Encode(Keccak.OfAnEmptyString).Bytes, Serialization.Rlp.Rlp.Encode(Keccak.OfAnEmptySequenceRlp).Bytes, Serialization.Rlp.Rlp.Encode(Keccak.OfAnEmptyString).Bytes.Concat(new byte[100000]).ToArray(), Serialization.Rlp.Rlp.Encode(Keccak.Compute("a")).Bytes.Concat(new byte[100000]).ToArray() }; }
public void Make_deposit_verify_incorrect_id() { DepositService depositService = new DepositService(_bridge, _txPool, _abiEncoder, _wallet, _contractAddress, LimboLogs.Instance); Deposit deposit = new Deposit(Keccak.Compute("a secret"), 10, (uint)new Timestamper().EpochSeconds + 86000, 1.Ether()); Keccak depositTxHash = depositService.MakeDeposit(_consumerAccount, deposit); _bridge.IncrementNonce(_consumerAccount); TxReceipt depositTxReceipt = _bridge.GetReceipt(depositTxHash); Assert.AreEqual(StatusCode.Success, depositTxReceipt.StatusCode, $"deposit made {depositTxReceipt.Error} {Encoding.UTF8.GetString(depositTxReceipt.ReturnValue ?? new byte[0])}"); Assert.AreEqual(0U, depositService.VerifyDeposit(_consumerAccount, Keccak.Compute("incorrect id")), "deposit verified"); }
public static Keccak CalculateHash(BlockHeader header) { using (MemoryStream stream = Rlp.BorrowStream()) { Rlp.Encode(stream, header); byte[] buffer = _rlpBuffer.Value; stream.Seek(0, SeekOrigin.Begin); stream.Read(buffer, 0, (int) stream.Length); Keccak newOne = Keccak.Compute(buffer.AsSpan().Slice(0, (int) stream.Length)); return newOne; } }
public void Returns_a_valid_balance() { DepositService depositService = new DepositService(_bridge, _txPool, _abiEncoder, _wallet, _contractAddress, LimboLogs.Instance); Deposit deposit = new Deposit(Keccak.Compute("a secret"), 10, (uint)new Timestamper().EpochSeconds + 86000, 1.Ether()); Keccak depositTxHash = depositService.MakeDeposit(_consumerAccount, deposit); _bridge.IncrementNonce(_consumerAccount); TxReceipt depositTxReceipt = _bridge.GetReceipt(depositTxHash); UInt256 balance = depositService.ReadDepositBalance(_consumerAccount, deposit.Id); Assert.AreEqual(balance, 1.Ether()); }
public void Can_claim_refund() { uint timestamp = 1546871954; _bridge.NextBlockPlease(timestamp); DepositService depositService = new DepositService(_bridge, _abiEncoder, _wallet, _ndmConfig, LimboLogs.Instance); Keccak headerId = Keccak.Compute("data header"); uint expiryTime = timestamp + 4; UInt256 value = 1.Ether(); uint units = 10U; byte[] salt = new byte[16]; AbiSignature depositAbiDef = new AbiSignature("deposit", new AbiBytes(32), new AbiUInt(32), new AbiUInt(96), new AbiUInt(32), new AbiBytes(16), AbiType.Address, AbiType.Address); byte[] depositData = _abiEncoder.Encode(AbiEncodingStyle.Packed, depositAbiDef, headerId.Bytes, units, value, expiryTime, salt, _providerAccount, _consumerAccount); Keccak depositId = Keccak.Compute(depositData); Deposit deposit = new Deposit(depositId, units, expiryTime, value); Keccak depositTxHash = depositService.MakeDeposit(_consumerAccount, deposit); TxReceipt depositTxReceipt = _bridge.GetReceipt(depositTxHash); TestContext.WriteLine("GAS USED FOR DEPOSIT: {0}", depositTxReceipt.GasUsed); Assert.AreEqual(StatusCode.Success, depositTxReceipt.StatusCode, $"deposit made {depositTxReceipt.Error} {Encoding.UTF8.GetString(depositTxReceipt.ReturnValue ?? new byte[0])}"); // calls revert and cannot reuse the same state - use only for manual debugging // Assert.True(depositService.VerifyDeposit(deposit.Id), "deposit verified"); RefundService refundService = new RefundService(_bridge, _abiEncoder, _wallet, _ndmConfig, LimboLogs.Instance); // it will not work so far as we do everything within the same block and timestamp is wrong _bridge.NextBlockPlease(expiryTime + 1); RefundClaim refundClaim = new RefundClaim(depositId, headerId, units, value, expiryTime, salt, _providerAccount, _consumerAccount); UInt256 balanceBefore = _state.GetBalance(_consumerAccount); Keccak refundTxHash = refundService.ClaimRefund(_consumerAccount, refundClaim); TxReceipt refundReceipt = _bridge.GetReceipt(refundTxHash); TestContext.WriteLine("GAS USED FOR REFUND CLAIM: {0}", refundReceipt.GasUsed); Assert.AreEqual(StatusCode.Success, refundReceipt.StatusCode, $"refund claim {refundReceipt.Error} {Encoding.UTF8.GetString(refundReceipt.ReturnValue ?? new byte[0])}"); UInt256 balanceAfter = _state.GetBalance(_consumerAccount); Assert.Greater(balanceAfter, balanceBefore); }
public IEnumerable <Node> GetClosestNodes(byte[] nodeId) { CheckInitialization(); Keccak idHash = Keccak.Compute(nodeId); return(Buckets.SelectMany(x => x.BondedItems) .Where(x => x.Node.IdHash != idHash) .Select(x => new { x.Node, Distance = _nodeDistanceCalculator.CalculateDistance(x.Node.Id.Bytes, nodeId) }) .OrderBy(x => x.Distance) .Take(_discoveryConfig.BucketSize) .Select(x => x.Node)); }
public void Delete_missing_resolved_on_leaf() { PatriciaTree patriciaTree = new PatriciaTree(_db, Keccak.EmptyTreeHash, false, true); patriciaTree.Set(Keccak.Compute("1234567").Bytes, new byte[] { 1 }); patriciaTree.Set(Keccak.Compute("1234501").Bytes, new byte[] { 2 }); patriciaTree.UpdateRootHash(); Keccak rootBefore = patriciaTree.RootHash; patriciaTree.Set(Keccak.Compute("1234502").Bytes, new byte[0]); patriciaTree.UpdateRootHash(); Assert.AreEqual(rootBefore, patriciaTree.RootHash); }
public void RoundTripWithRequiredData() { AnnounceMessage announceMessage = new AnnounceMessage(); announceMessage.HeadHash = Keccak.Compute("1"); announceMessage.HeadBlockNo = 4; announceMessage.TotalDifficulty = 131200; announceMessage.ReorgDepth = 0; AnnounceMessageSerializer serializer = new AnnounceMessageSerializer(); SerializerTester.TestZero(serializer, announceMessage, "e8a0c89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6048302008080c0"); }
private void BuildNodeInfo() { _nodeInfo = new NodeInfo(); _nodeInfo.Name = ClientVersion.Description; _nodeInfo.Enode = _enode.Info; byte[] publicKeyBytes = _enode.PublicKey?.Bytes; _nodeInfo.Id = (publicKeyBytes == null ? Keccak.Zero : Keccak.Compute(publicKeyBytes)).ToString(false); _nodeInfo.Ip = _enode.HostIp?.ToString(); _nodeInfo.ListenAddress = $"{_enode.HostIp}:{_enode.Port}"; _nodeInfo.Ports.Discovery = _networkConfig.DiscoveryPort; _nodeInfo.Ports.Listener = _networkConfig.P2PPort; UpdateEthProtocolInfo(); }
/// <summary> /// Suggested block validation runs basic checks that can be executed before going through the expensive EVM processing. /// </summary> /// <param name="block">A block to validate</param> /// <returns><value>True</value> if the <paramref name="block"/> is valid, otherwise <value>False</value></returns> public bool ValidateSuggestedBlock(Block block) { Transaction[] txs = block.Transactions; for (int i = 0; i < txs.Length; i++) { if (!_txValidator.IsWellFormed(txs[i], _specProvider.GetSpec(block.Number))) { if (_logger.IsDebug) { _logger.Debug($"Invalid block ({block.ToString(Block.Format.FullHashAndNumber)}) - invalid transaction ({txs[i].Hash})"); } return(false); } } if (!_ommersValidator.Validate(block.Header, block.Ommers)) { _logger?.Debug($"Invalid block ({block.ToString(Block.Format.FullHashAndNumber)}) - invalid ommers"); return(false); } bool blockHeaderValid = _headerValidator.Validate(block.Header); if (!blockHeaderValid) { if (_logger.IsDebug) { _logger.Debug($"Invalid block ({block.ToString(Block.Format.FullHashAndNumber)}) - invalid header"); } return(false); } if (block.Header.OmmersHash != Keccak.Compute(Rlp.Encode(block.Ommers))) { _logger?.Debug($"Invalid block ({block.ToString(Block.Format.FullHashAndNumber)}) - invalid ommers hash"); return(false); } Keccak txRoot = block.CalculateTxRoot(); if (txRoot != block.Header.TransactionsRoot) { if (_logger.IsDebug) { _logger.Debug($"Invalid block ({block.ToString(Block.Format.FullHashAndNumber)}) tx root {txRoot} != stated tx root {block.Header.TransactionsRoot}"); } return(false); } return(true); }
public async Task Can_claim_series_of_payments() { DepositService depositService = new DepositService(_ndmBridge, _abiEncoder, _wallet, _contractAddress); Keccak assetId = Keccak.Compute("data asset"); uint expiryTime = 1547051589; BigInteger value = (BigInteger)336.Ether() / 100; uint units = 336U; byte[] salt = new byte[16]; AbiSignature depositAbiDef = new AbiSignature("deposit", new AbiBytes(32), new AbiUInt(32), new AbiUInt(96), new AbiUInt(32), new AbiBytes(16), AbiType.Address, AbiType.Address); byte[] depositData = _abiEncoder.Encode(AbiEncodingStyle.Packed, depositAbiDef, assetId.Bytes, units, value, expiryTime, salt, _providerAccount, _consumerAccount); Keccak depositId = Keccak.Compute(depositData); Deposit deposit = new Deposit(depositId, units, expiryTime, (UInt256)value); Keccak depositTxHash = await depositService.MakeDepositAsync(_consumerAccount, deposit, 20.GWei()); TxReceipt depositTxReceipt = _bridge.GetReceipt(depositTxHash); TestContext.WriteLine("GAS USED FOR DEPOSIT: {0}", depositTxReceipt.GasUsed); Assert.AreEqual(StatusCode.Success, depositTxReceipt.StatusCode, $"deposit made {depositTxReceipt.Error} {Encoding.UTF8.GetString(depositTxReceipt.ReturnValue ?? new byte[0])}"); // calls revert and cannot reuse the same state - use only for manual debugging // Assert.True(depositService.VerifyDeposit(deposit.Id), "deposit verified"); DataRequest dataRequest = new DataRequest(assetId, units, (UInt256)value, expiryTime, salt, _providerAccount, _consumerAccount, new Signature(new byte[65])); Assert.AreEqual(deposit.Id, depositId, "depositID"); await ClaimPaymentFor(dataRequest, depositId, 0, 27, _providerAccount); await ClaimPaymentFor(dataRequest, depositId, 28, 55, _providerAccount); await ClaimPaymentFor(dataRequest, depositId, 56, 83, _providerAccount); await ClaimPaymentFor(dataRequest, depositId, 84, 111, _providerAccount); await ClaimPaymentFor(dataRequest, depositId, 112, 139, _providerAccount); await ClaimPaymentFor(dataRequest, depositId, 140, 167, _providerAccount); await ClaimPaymentFor(dataRequest, depositId, 168, 195, _providerAccount); await ClaimPaymentFor(dataRequest, depositId, 196, 223, _providerAccount); await ClaimPaymentFor(dataRequest, depositId, 224, 251, _providerAccount); await ClaimPaymentFor(dataRequest, depositId, 252, 279, _providerAccount); await ClaimPaymentFor(dataRequest, depositId, 280, 307, _providerAccount); await ClaimPaymentFor(dataRequest, depositId, 308, 335, _providerAccount); }
public void Roundtrip() { StatusMessage statusMessage = new(); statusMessage.ProtocolVersion = 63; statusMessage.BestHash = Keccak.Compute("1"); statusMessage.GenesisHash = Keccak.Compute("0"); statusMessage.TotalDifficulty = 131200; statusMessage.ChainId = 1; StatusMessageSerializer serializer = new(); SerializerTester.TestZero(serializer, statusMessage, "f8483f0183020080a0c89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6a0044852b2a670ade5407e78fb2863c51de9fcb96542a07186fe3aeda6bb8a116d"); }
private static byte[] ComputeAddress(AbiSignature signature) { string[] argTypeNames = new string[signature.Types.Length]; for (int i = 0; i < signature.Types.Length; i++) { argTypeNames[i] = signature.Types[i].ToString(); } string typeList = string.Join(",", argTypeNames); string signatureString = $"{signature.Name}({typeList})"; Keccak signatureKeccak = Keccak.Compute(signatureString); return(signatureKeccak.Bytes.Slice(0, 4)); }
public Keccak CalculateCliqueHeaderHash(BlockHeader blockHeader) { int extraSeal = 65; int shortExtraLength = blockHeader.ExtraData.Length - extraSeal; byte[] fullExtraData = blockHeader.ExtraData; byte[] shortExtraData = blockHeader.ExtraData.Slice(0, shortExtraLength); blockHeader.ExtraData = shortExtraData; Rlp rlp = Rlp.Encode(blockHeader); Keccak sigHash = Keccak.Compute(rlp); blockHeader.ExtraData = fullExtraData; return(sigHash); }
public Result StoreKey(PrivateKey key, SecureString password) { var salt = _cryptoRandom.GenerateRandomBytes(32); var passBytes = password.ToByteArray(_keyStoreEncoding); var derivedKey = SCrypt.ComputeDerivedKey(passBytes, salt, _config.KdfparamsN, _config.KdfparamsR, _config.KdfparamsP, null, _config.KdfparamsDklen); var encryptKey = Keccak.Compute(derivedKey.Take(16).ToArray()).Bytes.Take(16).ToArray(); var encryptContent = key.KeyBytes; var iv = _cryptoRandom.GenerateRandomBytes(_config.IVSize); var cipher = _symmetricEncrypter.Encrypt(encryptContent, encryptKey, iv, _config.Cipher); if (cipher == null) { return(Result.Fail("Error during encryption")); } var mac = Keccak.Compute(derivedKey.Skip(_config.KdfparamsDklen - 16).Take(16).Concat(cipher).ToArray()).Bytes; string addressString = key.Address.ToString(false, false); var keyStoreItem = new KeyStoreItem { Address = addressString, Crypto = new Crypto { Cipher = _config.Cipher, CipherText = cipher.ToHexString(true), CipherParams = new CipherParams { IV = iv.ToHexString(true) }, KDF = _config.Kdf, KDFParams = new KdfParams { DkLen = _config.KdfparamsDklen, N = _config.KdfparamsN, P = _config.KdfparamsP, R = _config.KdfparamsR, Salt = salt.ToHexString(true) }, MAC = mac.ToHexString(true), }, Id = addressString, Version = Version }; return(StoreKey(key.Address, keyStoreItem)); }
public static Address OfContract(Address deployingAddress, Span <byte> salt, Span <byte> initCode) { // sha3(0xff ++ msg.sender ++ salt ++ sha3(init_code))) Span <byte> bytes = new byte[1 + ByteLength + 32 + salt.Length]; bytes[0] = 0xff; deployingAddress.Bytes.CopyTo(bytes.Slice(1, 20)); salt.CopyTo(bytes.Slice(21, salt.Length)); Keccak.Compute(initCode).Bytes.CopyTo(bytes.Slice(21 + salt.Length, 32)); Keccak contractAddressKeccak = Keccak.Compute(bytes); return(new Address(contractAddressKeccak)); }
public ResultWrapper <byte[]> personal_sign(byte[] message, Address address, string passphrase = null) { if (!_wallet.IsUnlocked(address)) { if (passphrase != null) { var notSecuredHere = passphrase.Secure(); _wallet.UnlockAccount(address, notSecuredHere); } } message = ToEthSignedMessage(message); return(ResultWrapper <byte[]> .Success(_wallet.Sign(Keccak.Compute(message), address).Bytes)); }
public void Hobbit() { StatusMessage message = new StatusMessage(); message.ProtocolVersion = 63; message.BestHash = Keccak.Compute("1"); message.GenesisHash = Keccak.Compute("0"); message.TotalDifficulty = 131200; message.ChainId = 1; StatusMessageSerializer serializer = new StatusMessageSerializer(); SerializerTester.TestZero(serializer, message); }
public void Equals_operator_works() { Address addressA = new Address(Keccak.Compute("a")); Address addressA2 = new Address(Keccak.Compute("a")); Address addressB = new Address(Keccak.Compute("b")); Assert.True(addressA == addressA2); // ReSharper disable once EqualExpressionComparison Assert.True(addressA == addressA); Assert.False(addressA == addressB); Assert.False(addressA == null); Assert.False(null == addressA); Assert.True((Address)null == null); }
private static string ByteArrayToHexViaLookup32(byte[] bytes, bool withZeroX, bool skipLeadingZeros, bool withEip55Checksum) { int leadingZeros = skipLeadingZeros ? CountLeadingZeros(bytes) : 0; char[] result = new char[bytes.Length * 2 + (withZeroX ? 2 : 0) - leadingZeros]; string hashHex = null; if (withEip55Checksum) { hashHex = Keccak.Compute(bytes.ToHexString(false)).ToString(false); } if (withZeroX) { result[0] = '0'; result[1] = 'x'; } for (int i = 0; i < bytes.Length; i++) { uint val = Lookup32[bytes[i]]; char char1 = (char)val; char char2 = (char)(val >> 16); if (leadingZeros <= i * 2) { result[2 * i + (withZeroX ? 2 : 0) - leadingZeros] = withEip55Checksum && char.IsLetter(char1) && hashHex[2 * i] > '7' ? char.ToUpper(char1) : char1; } if (leadingZeros <= i * 2 + 1) { result[2 * i + 1 + (withZeroX ? 2 : 0) - leadingZeros] = withEip55Checksum && char.IsLetter(char2) && hashHex[2 * i + 1] > '7' ? char.ToUpper(char2) : char2; } } if (skipLeadingZeros && result.Length == (withZeroX ? 2 : 0)) { return(withZeroX ? "0x0" : "0"); } return(new string(result)); }
public void SetUp() { Console.WriteLine("AAA"); Session session = new Session(8545, Substitute.For <IChannel>(), Substitute.For <IDisconnectsAnalyzer>(), LimboLogs.Instance); session.RemoteNodeId = TestItem.PublicKeyA; session.RemoteHost = "127.0.0.1"; session.RemotePort = 30303; _ser = new MessageSerializationService(); _ser.Register(new TransactionsMessageSerializer()); _ser.Register(new StatusMessageSerializer()); NodeStatsManager stats = new NodeStatsManager(TimerFactory.Default, LimboLogs.Instance); var ecdsa = new EthereumEcdsa(ChainId.Mainnet, LimboLogs.Instance); var tree = Build.A.BlockTree().TestObject; var stateProvider = new StateProvider(new TrieStore(new MemDb(), LimboLogs.Instance), new MemDb(), LimboLogs.Instance); var specProvider = MainnetSpecProvider.Instance; TxPool.TxPool txPool = new TxPool.TxPool( ecdsa, new ChainHeadInfoProvider(new FixedBlockChainHeadSpecProvider(MainnetSpecProvider.Instance), tree, stateProvider), new TxPoolConfig(), new TxValidator(ChainId.Mainnet), LimboLogs.Instance, new TransactionComparerProvider(specProvider, tree).GetDefaultComparer()); ISyncServer syncSrv = Substitute.For <ISyncServer>(); BlockHeader head = Build.A.BlockHeader.WithNumber(1).TestObject; syncSrv.Head.Returns(head); _handler = new Eth62ProtocolHandler(session, _ser, stats, syncSrv, txPool, ShouldGossip.Instance, LimboLogs.Instance); _handler.DisableTxFiltering(); StatusMessage statusMessage = new StatusMessage(); statusMessage.ProtocolVersion = 63; statusMessage.BestHash = Keccak.Compute("1"); statusMessage.GenesisHash = Keccak.Compute("0"); statusMessage.TotalDifficulty = 131200; statusMessage.ChainId = 1; IByteBuffer bufStatus = _ser.ZeroSerialize(statusMessage); _zeroPacket = new ZeroPacket(bufStatus); _zeroPacket.PacketType = bufStatus.ReadByte(); _handler.HandleMessage(_zeroPacket); Transaction tx = Build.A.Transaction.SignedAndResolved(ecdsa, TestItem.PrivateKeyA).TestObject; _txMsg = new TransactionsMessage(new[] { tx }); }
public void Can_decode() { BlockHeader header = Build.A.BlockHeader .WithMixHash(Keccak.Compute("mix_hash")) .WithNonce(1000) .TestObject; HeaderDecoder decoder = new HeaderDecoder(); Rlp rlp = decoder.Encode(header); BlockHeader decoded = decoder.Decode(new Rlp.ValueDecoderContext(rlp.Bytes)); decoded.Hash = BlockHeader.CalculateHash(decoded); Assert.AreEqual(header.Hash, decoded.Hash, "hash"); }
public void Roundtrip_with_fork_id_next_is_max() { StatusMessage statusMessage = new(); statusMessage.ProtocolVersion = 63; statusMessage.BestHash = Keccak.Compute("1"); statusMessage.GenesisHash = Keccak.Compute("0"); statusMessage.TotalDifficulty = 131200; statusMessage.ChainId = 1; statusMessage.ForkId = new ForkId(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, long.MaxValue); StatusMessageSerializer serializer = new(); SerializerTester.TestZero(serializer, statusMessage); }
public void RoundTripWithHash() { var ethMessage = new Network.P2P.Subprotocols.Eth.V62.Messages.GetBlockHeadersMessage(); ethMessage.StartBlockHash = Keccak.Compute("1"); ethMessage.MaxHeaders = 10; ethMessage.Skip = 2; ethMessage.Reverse = 0; var message = new GetBlockHeadersMessage(ethMessage, 2); GetBlockHeadersMessageSerializer serializer = new(); SerializerTester.TestZero(serializer, message, "e602e4a0c89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc60a0280"); }