public TransactionProcessor( ISpecProvider?specProvider, IStateProvider?stateProvider, IStorageProvider?storageProvider, IVirtualMachine?virtualMachine, ILogManager?logManager) { _logger = logManager?.GetClassLogger() ?? throw new ArgumentNullException(nameof(logManager)); _specProvider = specProvider ?? throw new ArgumentNullException(nameof(specProvider)); _virtualMachine = virtualMachine ?? throw new ArgumentNullException(nameof(virtualMachine)); _stateProvider = stateProvider ?? throw new ArgumentNullException(nameof(stateProvider)); _storageProvider = storageProvider ?? throw new ArgumentNullException(nameof(storageProvider)); _ecdsa = new EthereumEcdsa(specProvider.ChainId, logManager); }
private void RunTest(TransactionTest test, IReleaseSpec spec) { //TestContext.CurrentContext.Test.Properties.Set("Category", test.Network); // no longer public ValidTransactionTest validTest = test as ValidTransactionTest; Nethermind.Core.Transaction transaction; try { Rlp rlp = new(Bytes.FromHexString(test.Rlp)); transaction = Rlp.Decode <Nethermind.Core.Transaction>(rlp); } catch (Exception) { if (validTest == null) { return; } throw; } bool useChainId = transaction.Signature.V > 28UL; TxValidator validator = new(useChainId ? ChainId.Mainnet : 0UL); if (validTest != null) { Assert.AreEqual(validTest.Value, transaction.Value, "value"); Assert.AreEqual(validTest.Data, transaction.Data, "data"); Assert.AreEqual(validTest.GasLimit, transaction.GasLimit, "gasLimit"); Assert.AreEqual(validTest.GasPrice, transaction.GasPrice, "gasPrice"); Assert.AreEqual(validTest.Nonce, transaction.Nonce, "nonce"); Assert.AreEqual(validTest.To, transaction.To, "to"); Assert.True(validator.IsWellFormed(transaction, spec)); Signature expectedSignature = new(validTest.R, validTest.S, validTest.V); Assert.AreEqual(expectedSignature, transaction.Signature, "signature"); IEthereumEcdsa ecdsa = new EthereumEcdsa(useChainId ? ChainId.Mainnet : 0UL, LimboLogs.Instance); bool verified = ecdsa.Verify( validTest.Sender, transaction); Assert.True(verified); } else { Assert.False(validator.IsWellFormed(transaction, spec)); } }
public static INdmBlockchainBridge BuildABridge() { IDbProvider memDbProvider = TestMemDbProvider.Init(); StateReader stateReader = new StateReader( new TrieStore(memDbProvider.StateDb, LimboLogs.Instance), memDbProvider.CodeDb, LimboLogs.Instance); var trieStore = new TrieStore(memDbProvider.StateDb, LimboLogs.Instance); StateProvider stateProvider = new StateProvider(trieStore, memDbProvider.CodeDb, LimboLogs.Instance); IEthereumEcdsa ecdsa = new EthereumEcdsa(ChainId.Mainnet, LimboLogs.Instance); BlockTree blockTree = Build.A.BlockTree().OfChainLength(1).TestObject; MainnetSpecProvider specProvider = MainnetSpecProvider.Instance; ITransactionComparerProvider transactionComparerProvider = new TransactionComparerProvider(MainnetSpecProvider.Instance, blockTree); ITxPool txPool = new TxPool.TxPool( new InMemoryTxStorage(), ecdsa, new ChainHeadInfoProvider(specProvider, blockTree, stateProvider), new TxPoolConfig(), new TxValidator(specProvider.ChainId), LimboLogs.Instance, transactionComparerProvider.GetDefaultComparer()); IWallet wallet = new DevWallet(new WalletConfig(), LimboLogs.Instance); ReceiptsRecovery receiptsRecovery = new ReceiptsRecovery(ecdsa, specProvider); LogFinder logFinder = new LogFinder(blockTree, new InMemoryReceiptStorage(), NullBloomStorage.Instance, LimboLogs.Instance, receiptsRecovery, 1024); ReadOnlyTxProcessingEnv processingEnv = new ReadOnlyTxProcessingEnv( new ReadOnlyDbProvider(memDbProvider, false), new TrieStore(memDbProvider.StateDb, LimboLogs.Instance).AsReadOnly(memDbProvider.StateDb), new ReadOnlyBlockTree(blockTree), specProvider, LimboLogs.Instance); BlockchainBridge blockchainBridge = new BlockchainBridge( processingEnv, txPool, new InMemoryReceiptStorage(), NullFilterStore.Instance, NullFilterManager.Instance, ecdsa, Timestamper.Default, logFinder, specProvider, false, false); WalletTxSigner txSigner = new WalletTxSigner(wallet, ChainId.Mainnet); ITxSealer txSealer0 = new TxSealer(txSigner, Timestamper.Default); ITxSealer txSealer1 = new NonceReservingTxSealer(txSigner, Timestamper.Default, txPool); ITxSender txSender = new TxPoolSender(txPool, txSealer0, txSealer1); return(new NdmBlockchainBridge(blockchainBridge, blockTree, stateReader, txSender)); }
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 }); }
protected override Task AddBlocksOnStart() { EthereumEcdsa ecdsa = new EthereumEcdsa(ChainSpec.ChainId, LimboLogs.Instance); return(AddBlock( SignTransactions(ecdsa, TestItem.PrivateKeyA, TxPriorityContract.SetPriority(TestItem.AddressA, TxPriorityContract.Destination.FnSignatureEmpty, UInt256.One), TxPriorityContract.SetPriority(TestItem.AddressB, FnSignature, 3), TxPriorityContract.SetMinGasPrice(TestItem.AddressB, FnSignature, 2), TxPriorityContract.SetMinGasPrice(TestItem.AddressB, FnSignature, 4), TxPriorityContract.SetSendersWhitelist(TestItem.AddressA, TestItem.AddressB), TxPriorityContract.SetSendersWhitelist(TestItem.AddressA, TestItem.AddressC)) )); }
public TxTraceFilter( Address[]?fromAddresses, Address[]?toAddresses, int after, int?count, ISpecProvider specProvider, ILogManager logManager) { _fromAddresses = fromAddresses; _toAddresses = toAddresses; _after = after; _count = count; _specProvider = specProvider; _logger = logManager.GetClassLogger(); _ecdsa = new EthereumEcdsa(specProvider.ChainId, logManager); }
public async Task seal_can_recover_address() { _auRaStepCalculator.CurrentStep.Returns(11); _auRaValidator.IsValidSealer(_address, 11).Returns(true); var block = Build.A.Block.WithHeader(Build.A.BlockHeader.WithBeneficiary(_address).WithAura(11, null).TestObject).TestObject; block = await _auRaSealer.SealBlock(block, CancellationToken.None); var ecdsa = new EthereumEcdsa(new MordenSpecProvider(), NullLogManager.Instance); var signature = new Signature(block.Header.AuRaSignature); signature.V += Signature.VOffset; var recoveredAddress = ecdsa.RecoverAddress(signature, BlockHeader.CalculateHash(block.Header, RlpBehaviors.ForSealing)); recoveredAddress.Should().Be(_address); }
public async Task seal_can_recover_address() { _auRaStepCalculator.CurrentStep.Returns(11); _validSealerStrategy.IsValidSealer(Arg.Any <IList <Address> >(), _address, 11).Returns(true); var block = Build.A.Block.WithHeader(Build.A.BlockHeader.WithBeneficiary(_address).WithAura(11, null).TestObject).TestObject; block = await _auRaSealer.SealBlock(block, CancellationToken.None); var ecdsa = new EthereumEcdsa(ChainId.Morden, LimboLogs.Instance); var signature = new Signature(block.Header.AuRaSignature); signature.V += Signature.VOffset; var recoveredAddress = ecdsa.RecoverAddress(signature, block.Header.CalculateHash(RlpBehaviors.ForSealing)); recoveredAddress.Should().Be(_address); }
public async Task Can_enqueue_previously_shelved() { ISyncModeSelector syncModeSelector = Substitute.For <ISyncModeSelector>(); await SetupBeamProcessor(syncModeSelector); EthereumEcdsa ethereumEcdsa = new EthereumEcdsa(ChainId.Mainnet, LimboLogs.Instance); Block newBlock0 = Build.A.Block.WithParent(_blockTree.Head) .WithReceiptsRoot(new Keccak("0xeb82c315eaf2c2a5dfc1766b075263d80e8b3ab9cb690d5304cdf114fff26939")) .WithTransactions(Build.A.Transaction.SignedAndResolved(ethereumEcdsa, TestItem.PrivateKeyA).TestObject, Build.A.Transaction.SignedAndResolved(ethereumEcdsa, TestItem.PrivateKeyB).TestObject) .WithGasUsed(42000) .WithTotalDifficulty(_blockTree.Head.TotalDifficulty + 1).TestObject; Block newBlock1 = Build.A.Block.WithParent(newBlock0.Header) .WithReceiptsRoot(new Keccak("0xeb82c315eaf2c2a5dfc1766b075263d80e8b3ab9cb690d5304cdf114fff26939")) .WithTransactions(Build.A.Transaction.SignedAndResolved(ethereumEcdsa, TestItem.PrivateKeyA).TestObject, Build.A.Transaction.SignedAndResolved(ethereumEcdsa, TestItem.PrivateKeyB).TestObject) .WithGasUsed(42000) .WithTotalDifficulty(_blockTree.Head.TotalDifficulty + 2).TestObject; Block newBlock2 = Build.A.Block.WithParent(newBlock1.Header).WithReceiptsRoot(new Keccak("0xeb82c315eaf2c2a5dfc1766b075263d80e8b3ab9cb690d5304cdf114fff26939")) .WithTransactions(Build.A.Transaction.SignedAndResolved(ethereumEcdsa, TestItem.PrivateKeyA).TestObject, Build.A.Transaction.SignedAndResolved(ethereumEcdsa, TestItem.PrivateKeyB).TestObject).WithGasUsed(42000).WithTotalDifficulty(_blockTree.Head.TotalDifficulty + 3).TestObject; Block newBlock3 = Build.A.Block.WithParent(newBlock2.Header).WithReceiptsRoot(new Keccak("0xeb82c315eaf2c2a5dfc1766b075263d80e8b3ab9cb690d5304cdf114fff26939")) .WithTransactions(Build.A.Transaction.SignedAndResolved(ethereumEcdsa, TestItem.PrivateKeyA).TestObject, Build.A.Transaction.SignedAndResolved(ethereumEcdsa, TestItem.PrivateKeyB).TestObject).WithGasUsed(42000).WithTotalDifficulty(_blockTree.Head.TotalDifficulty + 4).TestObject; Block newBlock4 = Build.A.Block.WithParent(newBlock3.Header).WithReceiptsRoot(new Keccak("0xeb82c315eaf2c2a5dfc1766b075263d80e8b3ab9cb690d5304cdf114fff26939")) .WithTransactions(Build.A.Transaction.SignedAndResolved(ethereumEcdsa, TestItem.PrivateKeyA).TestObject, Build.A.Transaction.SignedAndResolved(ethereumEcdsa, TestItem.PrivateKeyB).TestObject).WithGasUsed(42000).WithTotalDifficulty(_blockTree.Head.TotalDifficulty + 5).TestObject; var args = new SyncModeChangedEventArgs(SyncMode.Beam, SyncMode.WaitingForBlock); _blockTree.SuggestBlock(newBlock0); syncModeSelector.Preparing += Raise.EventWith(args); _blockTree.SuggestBlock(newBlock1); syncModeSelector.Changing += Raise.EventWith(args); _blockTree.SuggestBlock(newBlock2); syncModeSelector.Changed += Raise.EventWith(args); _blockTree.SuggestBlock(newBlock3); syncModeSelector.Preparing += Raise.EventWith(new SyncModeChangedEventArgs(SyncMode.Beam, SyncMode.Full)); _blockTree.SuggestBlock(newBlock4); await Task.Delay(1000); // _blockchainProcessor.Received().Process(newBlock0, ProcessingOptions.Beam, NullBlockTracer.Instance); _blockchainProcessingQueue.Received().Enqueue(newBlock1, ProcessingOptions.StoreReceipts); _blockchainProcessingQueue.Received().Enqueue(newBlock2, ProcessingOptions.StoreReceipts); _blockchainProcessingQueue.Received().Enqueue(newBlock3, ProcessingOptions.StoreReceipts); _blockchainProcessingQueue.Received().Enqueue(newBlock4, ProcessingOptions.StoreReceipts); }
public ExtendedKey(EthereumEcdsa key, byte[] chainCode, uint depth = 0, uint childIndex = 0, byte[] fingerprint = null) { // Set our key and chain code. InternalKey = key ?? throw new ArgumentNullException("Given key cannot be null when initializing extended key."); ChainCode = chainCode ?? throw new ArgumentNullException("Given chain code cannot be null when initializing extended key."); // Verify the size of our chain code. if (ChainCode.Length != CHAIN_CODE_SIZE) { throw new ArgumentException($"Given chain code was not of the expected size. Expected: {CHAIN_CODE_SIZE}, Actual: {ChainCode.Length}."); } // Set our other values Depth = depth; ChildIndex = childIndex; Fingerprint = fingerprint; }
/// <summary> /// Obtains the public key for this current key instance (if private, derives public, if public, returns as is). /// </summary> /// <returns>Returns this key if it is a public key, otherwise obtains the public key from this key.</returns> public ExtendedKey GetExtendedPublicKey() { // If this is already a public key, return itself if (KeyType == EthereumEcdsaKeyType.Public) { return(this); } // This is a private key, so we derive our public key information // at this level from this private key. return(new ExtendedKey( EthereumEcdsa.Create(InternalKey.ToPublicKeyArray(), EthereumEcdsaKeyType.Public), ChainCode, Depth, ChildIndex, Fingerprint)); }
public void Valid_block_with_transactions_makes_it_is_processed_normally_if_beam_syncing_finished() { ISyncModeSelector syncModeSelector = Substitute.For <ISyncModeSelector>(); SetupBeamProcessor(syncModeSelector); syncModeSelector.Preparing += Raise.EventWith(new SyncModeChangedEventArgs(SyncMode.Beam, SyncMode.Full)); syncModeSelector.Changing += Raise.EventWith(new SyncModeChangedEventArgs(SyncMode.Beam, SyncMode.Full)); syncModeSelector.Changed += Raise.EventWith(new SyncModeChangedEventArgs(SyncMode.Beam, SyncMode.Full)); EthereumEcdsa ethereumEcdsa = new EthereumEcdsa(MainnetSpecProvider.Instance, LimboLogs.Instance); Block newBlock = Build.A.Block.WithParent(_blockTree.Head).WithReceiptsRoot(new Keccak("0xeb82c315eaf2c2a5dfc1766b075263d80e8b3ab9cb690d5304cdf114fff26939")).WithTransactions(Build.A.Transaction.SignedAndResolved(ethereumEcdsa, TestItem.PrivateKeyA, 10000000).TestObject, Build.A.Transaction.SignedAndResolved(ethereumEcdsa, TestItem.PrivateKeyB, 10000000).TestObject).WithGasUsed(42000).WithTotalDifficulty(_blockTree.Head.TotalDifficulty + 1).TestObject; _blockTree.SuggestBlock(newBlock); Thread.Sleep(1000); _blockchainProcessor.DidNotReceiveWithAnyArgs().Process(newBlock, ProcessingOptions.Beam, NullBlockTracer.Instance); _blockchainProcessingQueue.Received().Enqueue(newBlock, ProcessingOptions.StoreReceipts); }
public void Initialize() { var logger = LimboLogs.Instance; var specProvider = MainNetSpecProvider.Instance; var ethereumEcdsa = new EthereumEcdsa(specProvider, logger); var txStorage = new InMemoryTxStorage(); var txPool = new TxPool(txStorage, Timestamper.Default, ethereumEcdsa, specProvider, new TxPoolConfig(), new StateProvider(new StateDb(), new MemDb(), LimboLogs.Instance), LimboLogs.Instance); _parityModule = new ParityModule(new EthereumEcdsa(specProvider, logger), txPool, logger); var blockNumber = 1; var transaction = Build.A.Transaction.Signed(ethereumEcdsa, TestItem.PrivateKeyD, blockNumber) .WithSenderAddress(Address.FromNumber((UInt256)blockNumber)).TestObject; transaction.Signature.V = 37; txPool.AddTransaction(transaction, blockNumber); }
public static (BigInteger R, BigInteger S, byte V) Sign(EthereumEcdsa privateKey, BigInteger nonce, BigInteger gasPrice, BigInteger gasLimit, Address?to, BigInteger value, byte[] data, uint?chainID) { // Obtain our transaction hash to sign. byte[] hash = GetUnsignedHash(nonce, gasPrice, gasLimit, to, value, data, chainID); // Sign our data (byte RecoveryID, BigInteger r, BigInteger s)signature = privateKey.SignData(hash); // Set our r and s components. var r = signature.r; var s = signature.s; // Obtain our v parameter from recovery ID and set it var v = EthereumEcdsa.GetVFromRecoveryID(chainID, signature.RecoveryID); return(r, s, v); }
public void Can_sign_on_networks_with_chain_id(DevWalletType walletType, int chainId) { EthereumEcdsa ecdsa = new EthereumEcdsa(chainId, LimboLogs.Instance); IWallet wallet = SetupWallet(walletType); for (int i = 1; i <= (walletType == DevWalletType.Memory ? 10 : 3); i++) { Address signerAddress = wallet.GetAccounts()[0]; Transaction tx = new Transaction(); tx.SenderAddress = signerAddress; wallet.Sign(tx, chainId); Address recovered = ecdsa.RecoverAddress(tx); Assert.AreEqual(signerAddress, recovered, $"{i}"); Assert.AreEqual(chainId, tx.Signature.ChainId, "chainId"); } }
// Precompiles Below /// <summary> /// A precompiled contract which uses v,r,s + hash obtained from the message data to perform elliptic curve public key recovery to obtain a senders address. /// </summary> /// <param name="evm">The Ethereum Virtual Machine instance we are executing inside of.</param> private static EVMExecutionResult Precompile_ECRecover(MeadowEVM evm) { // Charge the gas for the precompile operation before processing. evm.GasState.Deduct(GasDefinitions.GAS_PRECOMPILE_ECRECOVER); // Obtain a memory representation of our data. Span <byte> messageData = new Span <byte>(evm.Message.Data); // We extract our signature information from message data (256-bit each) Span <byte> hash = messageData.Slice(0, EVMDefinitions.WORD_SIZE); BigInteger v = BigIntegerConverter.GetBigInteger(messageData.Slice(32, EVMDefinitions.WORD_SIZE)); BigInteger r = BigIntegerConverter.GetBigInteger(messageData.Slice(64, EVMDefinitions.WORD_SIZE)); BigInteger s = BigIntegerConverter.GetBigInteger(messageData.Slice(96, EVMDefinitions.WORD_SIZE)); // Verify we have a low r, s, and a valid v. if (r >= Secp256k1Curve.N || s >= Secp256k1Curve.N || v < 27 || v > 28) { // We failed v,r,s verification, so we stop executing. return(new EVMExecutionResult(evm, null, true)); } // Obtain our recovery id from v. byte recoveryID = EthereumEcdsa.GetRecoveryAndChainIDFromV((byte)v).recoveryId; // Try to get an address from this. If it fails, it will throw an exception. byte[] senderAddress = null; try { senderAddress = EthereumEcdsa.Recover(hash, recoveryID, r, s).GetPublicKeyHash(); } catch { // Recovery failed, so we stop executing. return(new EVMExecutionResult(evm, null, true)); } // The address portion is at the end, and we zero out the leading portion. for (int i = 0; i < senderAddress.Length - Address.ADDRESS_SIZE; i++) { senderAddress[i] = 0; } // Return the sender address return(new EVMExecutionResult(evm, senderAddress, true)); }
public static INdmBlockchainBridge BuildABridge() { MemDbProvider memDbProvider = new MemDbProvider(); StateReader stateReader = new StateReader(memDbProvider.StateDb, memDbProvider.CodeDb, LimboLogs.Instance); StateProvider stateProvider = new StateProvider(memDbProvider.StateDb, memDbProvider.CodeDb, LimboLogs.Instance); StorageProvider storageProvider = new StorageProvider(memDbProvider.StateDb, stateProvider, LimboLogs.Instance); IEthereumEcdsa ecdsa = new EthereumEcdsa(MainNetSpecProvider.Instance, LimboLogs.Instance); ITxPool txPool = new TxPool.TxPool(new InMemoryTxStorage(), Timestamper.Default, ecdsa, MainNetSpecProvider.Instance, new TxPoolConfig(), stateProvider, LimboLogs.Instance); // BlockTree blockTree = new BlockTree(memDbProvider.BlocksDb, memDbProvider.HeadersDb, memDbProvider.BlockInfosDb, new ChainLevelInfoRepository(memDbProvider.BlockInfosDb), MainNetSpecProvider.Instance, txPool, NullBloomStorage.Instance, new SyncConfig(), LimboLogs.Instance); BlockTree blockTree = Build.A.BlockTree().OfChainLength(1).TestObject; IWallet wallet = new DevWallet(new WalletConfig(), LimboLogs.Instance); VirtualMachine virtualMachine = new VirtualMachine(stateProvider, storageProvider, new BlockhashProvider(blockTree, LimboLogs.Instance), MainNetSpecProvider.Instance, LimboLogs.Instance); TransactionProcessor processor = new TransactionProcessor(MainNetSpecProvider.Instance, stateProvider, storageProvider, virtualMachine, LimboLogs.Instance); BlockchainBridge blockchainBridge = new BlockchainBridge(stateReader, stateProvider, storageProvider, blockTree, txPool, new InMemoryReceiptStorage(), NullFilterStore.Instance, NullFilterManager.Instance, wallet, processor, ecdsa, NullBloomStorage.Instance, new ReceiptsRecovery()); return(new NdmBlockchainBridge(blockchainBridge, txPool)); }
public void Can_sign_on_networks_with_chain_id(DevWalletType walletType) { const int networkId = 40000; EthereumEcdsa ecdsa = new EthereumEcdsa(new SingleReleaseSpecProvider(Latest.Release, networkId), NullLogManager.Instance); IWallet wallet = SetupWallet(walletType); for (int i = 1; i <= (walletType == DevWalletType.Memory ? 10 : 3); i++) { Address signerAddress = wallet.GetAccounts()[0]; Transaction tx = new Transaction(); tx.SenderAddress = signerAddress; wallet.Sign(tx, networkId); Address recovered = ecdsa.RecoverAddress(tx, networkId); Assert.AreEqual(signerAddress, recovered, $"{i}"); Assert.AreEqual(networkId, tx.Signature.ChainId, "chainId"); } }
public void EciesEncryptDecryptTest() { string[] testDataSets = new string[] { "okayAESstrTest", "test2", "and another \x00 test. but this one is a sentence with \x11 weird characters." }; for (int i = 0; i < testDataSets.Length; i++) { // Generate a keypair EthereumEcdsa keypair = EthereumEcdsa.Generate(); byte[] testData = Encoding.UTF8.GetBytes(testDataSets[i]); byte[] encrypted = Ecies.Encrypt(keypair, testData, null); byte[] decrypted = Ecies.Decrypt(keypair, encrypted, null); string result = Encoding.UTF8.GetString(decrypted); Assert.Equal(testDataSets[i], result); } }
/// <summary> /// Initializes the extended key from the provided seed. /// </summary> /// <param name="seed">The seed to initialize this extended key from.</param> private void InitializeFromSeed(byte[] seed) { // Create a new HMACSHA512 instance HMACSHA512 hmacSha512 = new HMACSHA512(SeedHMACKey); // Compute the hash on our seed. byte[] hash = hmacSha512.ComputeHash(seed); // Set the key as the first 32 bytes of "hash" byte[] keyData = new byte[EthereumEcdsa.PRIVATE_KEY_SIZE]; Array.Copy(hash, 0, keyData, 0, keyData.Length); InternalKey = EthereumEcdsa.Create(keyData, EthereumEcdsaKeyType.Private); // Initialize the chain code ChainCode = new byte[CHAIN_CODE_SIZE]; // We derive the chain code as the data immediately following key data. Array.Copy(hash, 32, ChainCode, 0, ChainCode.Length); }
public void SignAndVerify(bool useBouncyCastle) { // Generate ECDSA keypair, compute a hash, sign it, then recover the public key from the signature and verify it matches. EthereumEcdsa provider; if (useBouncyCastle) { provider = EthereumEcdsaBouncyCastle.Generate(new SystemRandomAccountDerivation()); } else { provider = EthereumEcdsaNative.Generate(new SystemRandomAccountDerivation()); } byte[] hash = KeccakHash.ComputeHashBytes(new byte[] { 11, 22, 33, 44 }); (byte RecoveryID, BigInteger r, BigInteger s)signature = provider.SignData(hash); EthereumEcdsa recovered = EthereumEcdsa.Recover(hash, signature.RecoveryID, signature.r, signature.s); Assert.True(provider.GetPublicKeyHash().ValuesEqual(recovered.GetPublicKeyHash())); }
public void should_ignore_transactions_with_insufficient_intrinsic_gas() { _txPool = CreatePool(_noTxStorage); EthereumEcdsa ecdsa = new EthereumEcdsa(ChainId.Mainnet, _logManager); Transaction tx = Build.A.Transaction .WithData(new byte[] { 127, 243, 106, 181, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 145, 162, 136, 9, 81, 126, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 188, 120, 128, 96, 158, 141, 79, 126, 233, 131, 209, 47, 215, 166, 85, 190, 220, 187, 180, 115, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 96, 44, 207, 221, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 233, 29, 21, 62, 11, 65, 81, 138, 44, 232, 221, 61, 121, 68, 250, 134, 52, 99, 169, 125, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 183, 211, 17, 226, 235, 85, 242, 246, 138, 148, 64, 218, 56, 231, 152, 146, 16, 185, 160, 94, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 22, 226, 139, 67, 163, 88, 22, 43, 150, 247, 11, 77, 225, 76, 152, 164, 70, 95, 37 }) .SignedAndResolved() .TestObject; AddTxResult result = _txPool.AddTransaction(tx, TxHandlingOptions.PersistentBroadcast); _txPool.GetPendingTransactions().Length.Should().Be(0); result.Should().Be(AddTxResult.Invalid); }
protected override Keccak Handle(byte[] transaction, IWeb3EthApi api) { PublicEntry publicEntry; try { Transaction tx = Rlp.Decode <Transaction>(transaction); EthereumEcdsa ecdsa = new EthereumEcdsa(MainnetSpecProvider.Instance, LimboLogs.Instance); tx.SenderAddress = ecdsa.RecoverAddress(tx, MainnetSpecProvider.IstanbulBlockNumber); tx.Timestamp = (UInt256)DateTimeOffset.UtcNow.ToUnixTimeSeconds(); publicEntry = new PublicEntry { Data = (tx.Data ?? tx.Init).ToByteString(), GasLimit = (ulong)tx.GasLimit, GasPrice = tx.GasPrice.ToUint256ByteString(), Nonce = (ulong)tx.Nonce, SenderAddress = tx.SenderAddress.Bytes.ToByteString(), ReceiverAddress = tx.To?.Bytes.ToByteString() ?? ByteString.Empty, Amount = tx.Value.ToUint256ByteString(), Signature = new Protocol.Cryptography.Signature { RawBytes = ByteString.CopyFrom((byte)1) } }; } catch { try { TransactionBroadcast transactionBroadcast = TransactionBroadcast.Parser.ParseFrom(transaction); publicEntry = transactionBroadcast.PublicEntry; } catch (Exception) { throw new InvalidDataException($"Transaction data could not be deserialized into a {nameof(PublicEntry)}"); } } return(api.SendTransaction(publicEntry)); }
public void FullHandshakeStandard(bool useEip8) { // Create the initiator and responder keypairs EthereumEcdsa initiatorKeyPair = EthereumEcdsa.Generate(); EthereumEcdsa initiatorEphemeralKeyPair = EthereumEcdsa.Generate(); EthereumEcdsa responderKeyPair = EthereumEcdsa.Generate(); EthereumEcdsa responderEphemeralKeypair = EthereumEcdsa.Generate(); // Initiate RLPx sessions for each role. RLPxSession initiatorSession = new RLPxSession(RLPxSessionRole.Initiator, initiatorKeyPair, initiatorEphemeralKeyPair, useEip8); RLPxSession responderSession = new RLPxSession(RLPxSessionRole.Responder, responderKeyPair, responderEphemeralKeypair); // Create authentication data (initiator) (should work) byte[] authData = initiatorSession.CreateAuthentiation(responderKeyPair); // Create authentication data (responder) (should fail, responder should only be receiving auth data, not creating it). Assert.Throws <Exception>(() => { responderSession.CreateAuthentiation(initiatorKeyPair); }); // Verify the authentication data (responder) (should work) responderSession.VerifyAuthentication(authData); // Verify the authentication data (initiator) (should fail, responder should only be creating auth data, not verifying/receiving it). Assert.Throws <Exception>(() => { initiatorSession.VerifyAuthentication(authData); }); // After verification, the responder session should have set it's EIP8 status accordingly based off of what was received. Assert.Equal(useEip8, responderSession.UsingEIP8Authentication); // Create an authentication acknowledgement (responder) (should work) byte[] authAckData = responderSession.CreateAuthenticationAcknowledgement(); // Create an authentication acknowledgement (initiator) (should fail, initiator should only receiving auth-ack) Assert.Throws <Exception>(() => { initiatorSession.CreateAuthenticationAcknowledgement(); }); // Verify the authentication acknowledgement (initiator) (should work) initiatorSession.VerifyAuthenticationAcknowledgement(authAckData); // Verify the authentication acknowledgement (responder) (should fail, responder should not be verifying/receiving auth-ack) Assert.Throws <Exception>(() => { responderSession.VerifyAuthenticationAcknowledgement(authAckData); }); }
public void ComputeECDHKeyTest(bool useBouncyCastle, string privateKeyStr, string publicKeyStr, string expectedSecretStr) { // Generate ECDSA keypair EthereumEcdsa privateKey = null; EthereumEcdsa publicKey = null; if (useBouncyCastle) { privateKey = new EthereumEcdsaBouncyCastle(privateKeyStr.HexToBytes(), EthereumEcdsaKeyType.Private); publicKey = new EthereumEcdsaBouncyCastle(publicKeyStr.HexToBytes(), EthereumEcdsaKeyType.Public); } else { privateKey = new EthereumEcdsaNative(privateKeyStr.HexToBytes(), EthereumEcdsaKeyType.Private); publicKey = new EthereumEcdsaNative(publicKeyStr.HexToBytes(), EthereumEcdsaKeyType.Public); } // Compute a shared key. byte[] data = privateKey.ComputeECDHKey(publicKey); Assert.Equal(expectedSecretStr, data.ToHexString(false)); }
public static INdmBlockchainBridge BuildABridge() { MemDbProvider memDbProvider = new MemDbProvider(); StateReader stateReader = new StateReader(memDbProvider.StateDb, memDbProvider.CodeDb, LimboLogs.Instance); StateProvider stateProvider = new StateProvider(memDbProvider.StateDb, memDbProvider.CodeDb, LimboLogs.Instance); StorageProvider storageProvider = new StorageProvider(memDbProvider.StateDb, stateProvider, LimboLogs.Instance); IEthereumEcdsa ecdsa = new EthereumEcdsa(ChainId.Mainnet, LimboLogs.Instance); ITxPool txPool = new TxPool.TxPool(new InMemoryTxStorage(), Timestamper.Default, ecdsa, MainnetSpecProvider.Instance, new TxPoolConfig(), stateProvider, LimboLogs.Instance); // BlockTree blockTree = new BlockTree(memDbProvider.BlocksDb, memDbProvider.HeadersDb, memDbProvider.BlockInfosDb, new ChainLevelInfoRepository(memDbProvider.BlockInfosDb), MainnetSpecProvider.Instance, txPool, NullBloomStorage.Instance, new SyncConfig(), LimboLogs.Instance); BlockTree blockTree = Build.A.BlockTree().OfChainLength(1).TestObject; IWallet wallet = new DevWallet(new WalletConfig(), LimboLogs.Instance); VirtualMachine virtualMachine = new VirtualMachine(stateProvider, storageProvider, new BlockhashProvider(blockTree, LimboLogs.Instance), MainnetSpecProvider.Instance, LimboLogs.Instance); TransactionProcessor processor = new TransactionProcessor(MainnetSpecProvider.Instance, stateProvider, storageProvider, virtualMachine, LimboLogs.Instance); ReadOnlyTxProcessingEnv processingEnv = new ReadOnlyTxProcessingEnv( new ReadOnlyDbProvider(memDbProvider, false), new ReadOnlyBlockTree(blockTree), MainnetSpecProvider.Instance, LimboLogs.Instance); BlockchainBridge blockchainBridge = new BlockchainBridge( processingEnv, txPool, new InMemoryReceiptStorage(), NullFilterStore.Instance, NullFilterManager.Instance, ecdsa, NullBloomStorage.Instance, Timestamper.Default, LimboLogs.Instance, false, false); WalletTxSigner txSigner = new WalletTxSigner(wallet, ChainId.Mainnet); ITxSealer txSealer0 = new TxSealer(txSigner, Timestamper.Default); ITxSealer txSealer1 = new NonceReservingTxSealer(txSigner, Timestamper.Default, txPool); ITxSender txSender = new TxPoolSender(txPool, txSealer0, txSealer1); return(new NdmBlockchainBridge(blockchainBridge, blockTree, stateReader, txSender)); }
public void parity_netPeers_empty_ActivePeers() { LimboLogs logger = LimboLogs.Instance; MainnetSpecProvider specProvider = MainnetSpecProvider.Instance; EthereumEcdsa ethereumEcdsa = new EthereumEcdsa(specProvider.ChainId, logger); InMemoryTxStorage txStorage = new InMemoryTxStorage(); IDb blockDb = new MemDb(); IDb headerDb = new MemDb(); IDb blockInfoDb = new MemDb(); IBlockTree blockTree = new BlockTree(blockDb, headerDb, blockInfoDb, new ChainLevelInfoRepository(blockInfoDb), specProvider, NullBloomStorage.Instance, LimboLogs.Instance); ITransactionComparerProvider transactionComparerProvider = new TransactionComparerProvider(specProvider, blockTree); TxPool.TxPool txPool = new TxPool.TxPool(txStorage, ethereumEcdsa, new ChainHeadInfoProvider(new FixedBlockChainHeadSpecProvider(specProvider), blockTree, new StateProvider(new TrieStore(new MemDb(), LimboLogs.Instance), new MemDb(), LimboLogs.Instance)), new TxPoolConfig(), new TxValidator(specProvider.ChainId), LimboLogs.Instance, transactionComparerProvider.GetDefaultComparer()); new OnChainTxWatcher(blockTree, txPool, specProvider, LimboLogs.Instance); IReceiptStorage receiptStorage = new InMemoryReceiptStorage(); IPeerManager peerManager = Substitute.For <IPeerManager>(); peerManager.ActivePeers.Returns(new List <Peer> { }); peerManager.ConnectedPeers.Returns(new List <Peer> { new Peer(new Node("111.1.1.1", 11111, true)) }); IParityRpcModule parityRpcModule = new ParityRpcModule(ethereumEcdsa, txPool, blockTree, receiptStorage, new Enode(TestItem.PublicKeyA, IPAddress.Loopback, 8545), _signerStore, new MemKeyStore(new[] { TestItem.PrivateKeyA }), logger, peerManager); string serialized = RpcTest.TestSerializedRequest(parityRpcModule, "parity_netPeers"); string expectedResult = "{\"jsonrpc\":\"2.0\",\"result\":{\"active\":0,\"connected\":1,\"max\":0,\"peers\":[]},\"id\":67}"; Assert.AreEqual(expectedResult, serialized); }
public RLPxSession(RLPxSessionRole role, EthereumEcdsa localPrivateKey, EthereumEcdsa ephemeralPrivateKey, bool usingEIP8 = false) { // Verify the private key is not null if (localPrivateKey == null) { throw new ArgumentNullException("Provided local private key for RLPx session was null."); } // Verify the private key is a private key if (localPrivateKey.KeyType != EthereumEcdsaKeyType.Private) { throw new ArgumentException("Provided local private key for RLPx session was not a valid private key."); } // Set the local private key LocalPrivateKey = localPrivateKey; // Verify the ephemeral private key is a private key if (ephemeralPrivateKey != null && ephemeralPrivateKey.KeyType != EthereumEcdsaKeyType.Private) { throw new ArgumentException("Provided local private key for RLPx session was not a valid private key."); } // Set the ephemeral private key. LocalEphemeralPrivateKey = ephemeralPrivateKey ?? EthereumEcdsa.Generate(); // Set the role and session state Role = role; SessionState = RLPxSessionState.Initial; // Set the auth type if we are initiator. if (Role == RLPxSessionRole.Initiator) { UsingEIP8Authentication = usingEIP8; } }
protected virtual async Task <TestBlockchain> Build(ISpecProvider specProvider = null, UInt256?initialValues = null) { Timestamper = new ManualTimestamper(new DateTime(2020, 2, 15, 12, 50, 30, DateTimeKind.Utc)); JsonSerializer = new EthereumJsonSerializer(); SpecProvider = specProvider ?? MainnetSpecProvider.Instance; EthereumEcdsa = new EthereumEcdsa(ChainId.Mainnet, LimboLogs.Instance); ITxStorage txStorage = new InMemoryTxStorage(); DbProvider = await TestMemDbProvider.InitAsync(); State = new StateProvider(StateDb, CodeDb, LimboLogs.Instance); State.CreateAccount(TestItem.AddressA, (initialValues ?? 1000.Ether())); State.CreateAccount(TestItem.AddressB, (initialValues ?? 1000.Ether())); State.CreateAccount(TestItem.AddressC, (initialValues ?? 1000.Ether())); byte[] code = Bytes.FromHexString("0xabcd"); Keccak codeHash = Keccak.Compute(code); State.UpdateCode(code); State.UpdateCodeHash(TestItem.AddressA, codeHash, SpecProvider.GenesisSpec); Storage = new StorageProvider(StateDb, State, LimboLogs.Instance); Storage.Set(new StorageCell(TestItem.AddressA, UInt256.One), Bytes.FromHexString("0xabcdef")); Storage.Commit(); State.Commit(SpecProvider.GenesisSpec); State.CommitTree(); TxPool = new TxPool.TxPool( txStorage, EthereumEcdsa, SpecProvider, new TxPoolConfig(), new StateProvider(StateDb, CodeDb, LimboLogs.Instance), LimboLogs.Instance); IDb blockDb = new MemDb(); IDb headerDb = new MemDb(); IDb blockInfoDb = new MemDb(); BlockTree = new BlockTree(blockDb, headerDb, blockInfoDb, new ChainLevelInfoRepository(blockDb), SpecProvider, NullBloomStorage.Instance, LimboLogs.Instance); new OnChainTxWatcher(BlockTree, TxPool, SpecProvider, LimboLogs.Instance); ReceiptStorage = new InMemoryReceiptStorage(); VirtualMachine virtualMachine = new VirtualMachine(State, Storage, new BlockhashProvider(BlockTree, LimboLogs.Instance), SpecProvider, LimboLogs.Instance); TxProcessor = new TransactionProcessor(SpecProvider, State, Storage, virtualMachine, LimboLogs.Instance); BlockProcessor = CreateBlockProcessor(); BlockchainProcessor chainProcessor = new BlockchainProcessor(BlockTree, BlockProcessor, new RecoverSignatures(EthereumEcdsa, TxPool, SpecProvider, LimboLogs.Instance), LimboLogs.Instance, Nethermind.Blockchain.Processing.BlockchainProcessor.Options.Default); BlockchainProcessor = chainProcessor; chainProcessor.Start(); StateReader = new StateReader(StateDb, CodeDb, LimboLogs.Instance); TxPoolTxSource txPoolTxSource = CreateTxPoolTxSource(); ISealer sealer = new NethDevSealEngine(TestItem.AddressD); BlockProducer = new TestBlockProducer(txPoolTxSource, chainProcessor, State, sealer, BlockTree, chainProcessor, Timestamper, LimboLogs.Instance); BlockProducer.Start(); _resetEvent = new SemaphoreSlim(0); _suggestedBlockResetEvent = new ManualResetEvent(true); BlockTree.NewHeadBlock += (s, e) => { _resetEvent.Release(1); }; BlockProducer.LastProducedBlockChanged += (s, e) => { _suggestedBlockResetEvent.Set(); }; var genesis = GetGenesisBlock(); BlockTree.SuggestBlock(genesis); await _resetEvent.WaitAsync(); //if (!await _resetEvent.WaitAsync(1000)) // { // throw new InvalidOperationException("Failed to process genesis in 1s."); // } await AddBlocksOnStart(); return(this); }
public void Initialize() { var logger = LimboLogs.Instance; var specProvider = MainnetSpecProvider.Instance; var ethereumEcdsa = new EthereumEcdsa(specProvider.ChainId, logger); var txStorage = new InMemoryTxStorage(); Peer peerA = SetUpPeerA(); //standard case Peer peerB = SetUpPeerB(); //Session is null Peer peerC = SetUpPeerC(); //Node is null, Caps are empty IPeerManager peerManager = Substitute.For <IPeerManager>(); peerManager.ActivePeers.Returns(new List <Peer> { peerA, peerB, peerC }); peerManager.ConnectedPeers.Returns(new List <Peer> { peerA, peerB, peerA, peerC, peerB }); peerManager.MaxActivePeers.Returns(15); StateProvider stateProvider = new StateProvider(new TrieStore(new MemDb(), LimboLogs.Instance), new MemDb(), LimboLogs.Instance); var txPool = new TxPool.TxPool(txStorage, ethereumEcdsa, new FixedBlockChainHeadSpecProvider(specProvider), new TxPoolConfig(), stateProvider, new TxValidator(specProvider.ChainId), LimboLogs.Instance); IDb blockDb = new MemDb(); IDb headerDb = new MemDb(); IDb blockInfoDb = new MemDb(); IBlockTree blockTree = new BlockTree(blockDb, headerDb, blockInfoDb, new ChainLevelInfoRepository(blockInfoDb), specProvider, NullBloomStorage.Instance, LimboLogs.Instance); new OnChainTxWatcher(blockTree, txPool, specProvider, LimboLogs.Instance); IReceiptStorage receiptStorage = new InMemoryReceiptStorage(); _signerStore = new Signer(specProvider.ChainId, TestItem.PrivateKeyB, logger); _parityModule = new ParityModule(ethereumEcdsa, txPool, blockTree, receiptStorage, new Enode(TestItem.PublicKeyA, IPAddress.Loopback, 8545), _signerStore, new MemKeyStore(new[] { TestItem.PrivateKeyA }), logger, peerManager); var blockNumber = 2; var pendingTransaction = Build.A.Transaction.Signed(ethereumEcdsa, TestItem.PrivateKeyD, false) .WithSenderAddress(Address.FromNumber((UInt256)blockNumber)).TestObject; pendingTransaction.Signature.V = 37; stateProvider.CreateAccount(pendingTransaction.SenderAddress, UInt256.UInt128MaxValue); txPool.AddTransaction(pendingTransaction, TxHandlingOptions.None); blockNumber = 1; var transaction = Build.A.Transaction.Signed(ethereumEcdsa, TestItem.PrivateKeyD, false) .WithSenderAddress(Address.FromNumber((UInt256)blockNumber)) .WithNonce(100).TestObject; transaction.Signature.V = 37; stateProvider.CreateAccount(transaction.SenderAddress, UInt256.UInt128MaxValue); txPool.AddTransaction(transaction, TxHandlingOptions.None); Block genesis = Build.A.Block.Genesis .WithStateRoot(new Keccak("0x1ef7300d8961797263939a3d29bbba4ccf1702fabf02d8ad7a20b454edb6fd2f")) .TestObject; blockTree.SuggestBlock(genesis); blockTree.UpdateMainChain(new[] { genesis }, true); Block previousBlock = genesis; Block block = Build.A.Block.WithNumber(blockNumber).WithParent(previousBlock) .WithStateRoot(new Keccak("0x1ef7300d8961797263939a3d29bbba4ccf1702fabf02d8ad7a20b454edb6fd2f")) .WithTransactions(MuirGlacier.Instance, transaction) .TestObject; blockTree.SuggestBlock(block); blockTree.UpdateMainChain(new[] { block }, true); var logEntries = new[] { Build.A.LogEntry.TestObject }; receiptStorage.Insert(block, new TxReceipt() { Bloom = new Bloom(logEntries), Index = 1, Recipient = TestItem.AddressA, Sender = TestItem.AddressB, BlockHash = TestItem.KeccakA, BlockNumber = 1, ContractAddress = TestItem.AddressC, GasUsed = 1000, TxHash = transaction.Hash, StatusCode = 0, GasUsedTotal = 2000, Logs = logEntries }); }