public static string TestSerializedRequest <T>(IReadOnlyCollection <JsonConverter> converters, T module, string method, params string[] parameters) where T : class, IModule { IJsonRpcService service = BuildRpcService(module); JsonRpcRequest request = GetJsonRequest(method, parameters); JsonRpcResponse response = service.SendRequestAsync(request).Result; EthereumJsonSerializer serializer = new EthereumJsonSerializer(); foreach (JsonConverter converter in converters) { serializer.RegisterConverter(converter); } Stream stream = new MemoryStream(); serializer.Serialize(stream, response); // for coverage (and to prove that it does not throw Stream indentedStream = new MemoryStream(); serializer.Serialize(indentedStream, response, true); stream.Seek(0, SeekOrigin.Begin); string serialized = new StreamReader(stream).ReadToEnd(); TestContext.Out?.WriteLine("Serialized:"); TestContext.Out?.WriteLine(serialized); return(serialized); }
public void can_serialize_valid_accessList() { _transaction = new Transaction(); _transaction.Type = TxType.AccessList; _transaction.AccessList = GetTestAccessList(); _transactionForRpc = new TransactionForRpc(_transaction); string serialized = _serializer.Serialize(_transactionForRpc); string expected = "{\"nonce\":\"0x0\",\"blockHash\":null,\"blockNumber\":null,\"transactionIndex\":null,\"to\":null,\"value\":\"0x0\",\"gasPrice\":\"0x0\",\"gas\":\"0x0\",\"input\":null,\"type\":\"0x01\",\"accessList\":[{\"address\":\"0xb7705ae4c6f81b66cdb323c65f4e8133690fc099\",\"storageKeys\":[\"0x0000000000000000000000000000000000000000000000000000000000000001\",\"0x0000000000000000000000000000000000000000000000000000000000000002\",\"0x0000000000000000000000000000000000000000000000000000000000000003\",\"0x0000000000000000000000000000000000000000000000000000000000000005\",\"0x0000000000000000000000000000000000000000000000000000000000000008\"]},{\"address\":\"0x942921b14f1b1c385cd7e0cc2ef7abe5598c8358\",\"storageKeys\":[\"0x000000000000000000000000000000000000000000000000000000000000002a\"]}]}"; expected.Should().Be(serialized); }
private void LogDiagnosticTrace(IBlockTracer blockTracer) { GethLikeBlockTracer gethTracer = blockTracer as GethLikeBlockTracer; ParityLikeBlockTracer parityTracer = blockTracer as ParityLikeBlockTracer; if (gethTracer != null) { var serializer = new EthereumJsonSerializer(); var trace = gethTracer.BuildResult(); var serialized = serializer.Serialize(trace, true); if (_logger.IsInfo) { _logger.Info(serialized); } } if (parityTracer != null) { var serializer = new EthereumJsonSerializer(); var trace = parityTracer.BuildResult(); var serialized = serializer.Serialize(trace, true); if (_logger.IsInfo) { _logger.Info(serialized); } } }
private void LogDiagnosticTrace(IBlockTracer blockTracer, Block block) { FileStream GetDiagnosticFile() => new FileStream($"trace_{block}.txt", FileMode.Create, FileAccess.Write); GethLikeBlockTracer gethTracer = blockTracer as GethLikeBlockTracer; ParityLikeBlockTracer parityTracer = blockTracer as ParityLikeBlockTracer; if (gethTracer != null) { using var diagnosticFile = GetDiagnosticFile(); var serializer = new EthereumJsonSerializer(); var trace = gethTracer.BuildResult(); serializer.Serialize(diagnosticFile, trace, true); if (_logger.IsInfo) { _logger.Info($"Created trace of block {block} in file {diagnosticFile.Name}"); } } if (parityTracer != null) { using var diagnosticFile = GetDiagnosticFile(); var serializer = new EthereumJsonSerializer(); var trace = parityTracer.BuildResult(); serializer.Serialize(diagnosticFile, trace, true); if (_logger.IsInfo) { _logger.Info($"Created trace of block {block} in file {diagnosticFile.Name}"); } } }
public void Can_call_by_hash_canonical() { Block lastHead = _blockTree.Head; Block block = Build.A.Block.WithParent(lastHead).TestObject; Block newBlockOnMain = Build.A.Block.WithParent(lastHead).WithDifficulty(block.Difficulty + 1).TestObject; BlockTreeBuilder.AddBlock(_blockTree, block); BlockTreeBuilder.AddBlock(_blockTree, newBlockOnMain); // would need to setup state root somehow... TransactionForRpc tx = new TransactionForRpc { From = TestItem.AddressA, To = TestItem.AddressB, GasPrice = _useNonZeroGasPrice ? 10.GWei() : 0 }; EthereumJsonSerializer serializer = new EthereumJsonSerializer(); string response = RpcTest.TestSerializedRequest(_proofModule, "proof_call", $"{serializer.Serialize(tx)}", $"{{\"blockHash\" : \"{block.Hash}\", \"requireCanonical\" : true}}"); Assert.True(response.Contains("-32000")); response = RpcTest.TestSerializedRequest(_proofModule, "proof_call", $"{serializer.Serialize(tx)}", $"{{\"blockHash\" : \"{TestItem.KeccakG}\", \"requireCanonical\" : true}}"); Assert.True(response.Contains("-32001")); }
public Task Run(string[] args) { (CommandLineApplication app, var buildConfigProvider, var getDbBasePath) = BuildCommandLineApp(); ManualResetEventSlim appClosed = new ManualResetEventSlim(true); app.OnExecute(async() => { appClosed.Reset(); IConfigProvider configProvider = buildConfigProvider(); IInitConfig initConfig = configProvider.GetConfig <IInitConfig>(); _logger = new NLogLogger(initConfig.LogFileName, initConfig.LogDirectory); if (_logger.IsDebug) { _logger.Debug($"Nethermind version: {ClientVersion.Description}"); } LogMemoryConfiguration(); string?pathDbPath = getDbBasePath(); if (!string.IsNullOrWhiteSpace(pathDbPath)) { string newDbPath = Path.Combine(pathDbPath, initConfig.BaseDbPath); if (_logger.IsDebug) { _logger.Debug( $"Adding prefix to baseDbPath, new value: {newDbPath}, old value: {initConfig.BaseDbPath}"); } initConfig.BaseDbPath = newDbPath ?? Path.Combine(AppDomain.CurrentDomain.BaseDirectory ?? "", "db"); } Console.Title = initConfig.LogFileName; Console.CancelKeyPress += ConsoleOnCancelKeyPress; EthereumJsonSerializer serializer = new EthereumJsonSerializer(); if (_logger.IsDebug) { _logger.Debug($"Nethermind config:\n{serializer.Serialize(initConfig, true)}\n"); } _processExit = new TaskCompletionSource <object?>(); _cancelKeySource = new TaskCompletionSource <object?>(); await StartRunners(_processCloseCancellationSource.Token, configProvider); await Task.WhenAny(_cancelKeySource.Task, _processExit.Task); Console.WriteLine("Closing, please wait until all functions are stopped properly..."); StopAsync().Wait(); Console.WriteLine("All done, goodbye!"); appClosed.Set(); return(0); }); app.Execute(args); appClosed.Wait(); return(Task.CompletedTask); }
public void Can_Run_Smoke_test() { var code = Bytes.FromHexString("0x600060000100"); var txTracer = RunVirtualMachine(code); var serializer = new EthereumJsonSerializer(); var trace = txTracer.BuildResult(); _testOutputHelper.WriteLine(serializer.Serialize(trace, true)); }
public void CanHandleOptionalArguments() { EthereumJsonSerializer serializer = new EthereumJsonSerializer(); string serialized = serializer.Serialize(new TransactionForRpc()); IEthRpcModule ethRpcModule = Substitute.For<IEthRpcModule>(); ethRpcModule.eth_call(Arg.Any<TransactionForRpc>()).ReturnsForAnyArgs(x => ResultWrapper<string>.Success("0x1")); JsonRpcSuccessResponse response = TestRequest(ethRpcModule, "eth_call", serialized) as JsonRpcSuccessResponse; Assert.AreEqual("0x1", response?.Result); }
public void Can_Run_Smoke_test() { var code = Bytes.FromHexString("0x600060000100"); GethLikeTxTracer txTracer = RunVirtualMachine(code); EthereumJsonSerializer serializer = new EthereumJsonSerializer(); GethLikeTxTrace trace = txTracer.BuildResult(); TestContext.WriteLine(serializer.Serialize(trace, true)); }
public void CanHandleOptionalArguments() { EthereumJsonSerializer serializer = new EthereumJsonSerializer(); string serialized = serializer.Serialize(new TransactionForRpc()); IEthModule ethModule = Substitute.For <IEthModule>(); ethModule.eth_call(Arg.Any <TransactionForRpc>()).ReturnsForAnyArgs(x => ResultWrapper <byte[]> .Success(new byte[] { 1 })); JsonRpcResponse response = TestRequest <IEthModule>(ethModule, "eth_call", serialized); Assert.AreEqual(1, (response.Result as byte[]).Length); }
public void Can_Invoke_Origin() { var code = Bytes.FromHexString("0x3200"); GethLikeTxTracer txTracer = RunVirtualMachine(code); EthereumJsonSerializer serializer = new EthereumJsonSerializer(); GethLikeTxTrace trace = txTracer.BuildResult(); TestContext.WriteLine(serializer.Serialize(trace, true)); trace.Failed.Should().Be(false); trace.Entries.Last().Stack.Count.Should().Be(1); trace.Entries.Last().Stack.Last().Should().Be(VirtualMachine.BytesZero32.ToHexString()); }
public void Can_Invoke_Range_Proof_Precompile() { var code = Bytes.FromHexString("0x60008080806201000062050000F400"); var txTracer = RunVirtualMachine(code); var serializer = new EthereumJsonSerializer(); var trace = txTracer.BuildResult(); _testOutputHelper.WriteLine(serializer.Serialize(trace, true)); trace.Failed.Should().Be(false); trace.Entries.Last().Stack.Count.Should().Be(1); trace.Entries.Last().Stack.Last().Should().Be(VirtualMachine.BytesOne32.ToHexString()); }
public void Can_Invoke_Gas_Limit() { var code = Bytes.FromHexString("0x4500"); var txTracer = RunVirtualMachine(code); var serializer = new EthereumJsonSerializer(); var trace = txTracer.BuildResult(); _testOutputHelper.WriteLine(serializer.Serialize(trace, true)); trace.Failed.Should().Be(false); trace.Entries.Last().Stack.Count.Should().Be(1); trace.Entries.Last().Stack.Last().Should().Be("f4240".PadLeft(64, '0')); }
public void Can_Invoke_Address() { var code = Bytes.FromHexString("0x3000"); var txTracer = RunVirtualMachine(code); var serializer = new EthereumJsonSerializer(); var trace = txTracer.BuildResult(); _testOutputHelper.WriteLine(serializer.Serialize(trace, true)); trace.Failed.Should().Be(false); trace.Entries.Last().Stack.Count.Should().Be(1); trace.Entries.Last().Stack.Last().Should().Be(VirtualMachine.BytesZero32.ToHexString()); }
private void TestToJson <T>(T item, JsonConverter <T> converter, string expectedResult) { EthereumJsonSerializer serializer = BuildSerializer(); if (converter != null) { serializer.RegisterConverter(converter); } string result = serializer.Serialize(item); Assert.AreEqual(expectedResult, result, result.Replace("\"", "\\\"")); }
public void Blake_precompile() { Address blakeAddress = Address.FromNumber(1 + KatVirtualMachine.CatalystPrecompilesAddressingSpace); string addressCode = blakeAddress.Bytes.ToHexString(false); var code = Bytes.FromHexString("0x602060006080600073" + addressCode + "45fa00"); GethLikeTxTracer txTracer = RunVirtualMachine(code); EthereumJsonSerializer serializer = new EthereumJsonSerializer(); GethLikeTxTrace trace = txTracer.BuildResult(); TestContext.WriteLine(serializer.Serialize(trace, true)); trace.Entries.Last().Stack.First().Should().Be("0000000000000000000000000000000000000000000000000000000000000001"); trace.Entries.Last().Memory.First().Should().Be("378d0caaaa3855f1b38693c1d6ef004fd118691c95c959d4efa950d6d6fcf7c1"); }
public void Run(string[] args) { var(app, buildConfigProvider, getDbBasePath) = BuildCommandLineApp(); ManualResetEventSlim appClosed = new ManualResetEventSlim(true); app.OnExecute(async() => { appClosed.Reset(); var configProvider = buildConfigProvider(); var initConfig = configProvider.GetConfig <IInitConfig>(); LogManager.Configuration = new XmlLoggingConfiguration("NLog.config".GetApplicationResourcePath()); _logger = new NLogLogger(initConfig.LogFileName, initConfig.LogDirectory); LogMemoryConfiguration(); var pathDbPath = getDbBasePath(); if (!string.IsNullOrWhiteSpace(pathDbPath)) { var newDbPath = Path.Combine(pathDbPath, initConfig.BaseDbPath); if (_logger.IsDebug) { _logger.Debug($"Adding prefix to baseDbPath, new value: {newDbPath}, old value: {initConfig.BaseDbPath}"); } initConfig.BaseDbPath = newDbPath ?? Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "db"); } Console.Title = initConfig.LogFileName; Console.CancelKeyPress += ConsoleOnCancelKeyPress; var serializer = new EthereumJsonSerializer(); if (_logger.IsInfo) { _logger.Info($"Nethermind config:\n{serializer.Serialize(initConfig, true)}\n"); } _cancelKeySource = new TaskCompletionSource <object>(); await StartRunners(configProvider); await _cancelKeySource.Task; Console.WriteLine("Closing, please wait until all functions are stopped properly..."); StopAsync().Wait(); Console.WriteLine("All done, goodbye!"); appClosed.Set(); return(0); }); app.Execute(args); appClosed.Wait(); }
protected void TestRoundtrip <T>(string json, JsonConverter converter = null) { EthereumJsonSerializer serializer = BuildSerializer(); if (converter != null) { serializer.RegisterConverter(converter); } T deserialized = serializer.Deserialize <T>(json); string result = serializer.Serialize(deserialized); Assert.AreEqual(json, result); }
public void Init(string path) { var dbOnTheRocks = new BlocksRocksDb(path, new DbConfig(), LimboLogs.Instance); var blocksBytes = dbOnTheRocks.GetAll(); var blockDecoder = new BlockDecoder(); var blocks = blocksBytes .Select(b => blockDecoder.Decode(b.Value.AsRlpStream())) .OrderBy(b => b.Number) .ToList(); var window = new Window("Blocks") { X = 0, Y = 10, Width = Dim.Fill(), Height = Dim.Fill() }; if (!blocks.Any()) { MessageBox.Query(40, 7, "Info", "No data."); window.FocusPrev(); return; } var y = 1; foreach (var block in blocks) { var blockBtn = new Button(1, y++, $"Number: {block.Number}, Hash: {block.Hash}"); blockBtn.Clicked = () => { var blockDetailsWindow = new Window("Block details") { X = 0, Y = 10, Width = Dim.Fill(), Height = Dim.Fill() }; Application.Top.Add(blockDetailsWindow); var serializer = new EthereumJsonSerializer(); var blockLbl = new Label(1, 1, serializer.Serialize(block, true)); blockDetailsWindow.Add(blockLbl); Application.Run(blockDetailsWindow); }; window.Add(blockBtn); } Application.Top.Add(window); Application.Run(window); }
public void Init(string path) { var dbOnTheRocks = new PaymentClaimsRocksDb(path, new DbConfig(), LimboLogs.Instance); var paymentClaimsBytes = dbOnTheRocks.GetAll(); var paymentClaimsDecoder = new PaymentClaimDecoder(); var paymentClaims = paymentClaimsBytes .Select(b => paymentClaimsDecoder.Decode(b.Value.AsRlpStream())); var window = new Window("Payment claims") { X = 0, Y = 10, Width = Dim.Fill(), Height = Dim.Fill() }; if (!paymentClaims.Any()) { MessageBox.Query(40, 7, "Payment claims", "No data." + $"{Environment.NewLine}(ESC to close)"); window.FocusPrev(); return; } var y = 1; foreach (var paymentClaim in paymentClaims) { var paymentClaimBtn = new Button(1, y++, $"AssetName: {paymentClaim.AssetName}," + $"DepositId: {paymentClaim.DepositId}"); paymentClaimBtn.Clicked = () => { var paymentClaimsDetailsWindow = new Window("Payment claim details") { X = 0, Y = 10, Width = Dim.Fill(), Height = Dim.Fill() }; Application.Top.Add(paymentClaimsDetailsWindow); var serializer = new EthereumJsonSerializer(); var paymentClaimLbl = new Label(1, 1, serializer.Serialize(paymentClaim, true)); paymentClaimsDetailsWindow.Add(paymentClaimLbl); Application.Run(paymentClaimsDetailsWindow); }; window.Add(paymentClaimBtn); } Application.Top.Add(window); Application.Run(window); }
public void Init(string path) { var dbOnTheRocks = new DataAssetsRocksDb(path, new DbConfig(), LimboLogs.Instance); var dataAssetsBytes = dbOnTheRocks.GetAll(); var dataAssetDecoder = new DataAssetDecoder(); var dataAssets = dataAssetsBytes .Select(b => dataAssetDecoder.Decode(b.Value.AsRlpStream())); var window = new Window("Data assets") { X = 0, Y = 10, Width = Dim.Fill(), Height = Dim.Fill() }; if (!dataAssets.Any()) { MessageBox.Query(40, 7, "Data assets", "No data." + $"{Environment.NewLine}(ESC to close)"); window.FocusPrev(); return; } var y = 1; foreach (var dataAsset in dataAssets) { var dataAssetsBtn = new Button(1, y++, $"Name: {dataAsset.Name}"); dataAssetsBtn.Clicked = () => { var dataAssetDetailsWindow = new Window("Data asset details") { X = 0, Y = 10, Width = Dim.Fill(), Height = Dim.Fill() }; Application.Top.Add(dataAssetDetailsWindow); var serializer = new EthereumJsonSerializer(); var dataAssetLbl = new Label(1, 1, serializer.Serialize(dataAsset, true)); dataAssetDetailsWindow.Add(dataAssetLbl); Application.Run(dataAssetDetailsWindow); }; window.Add(dataAssetsBtn); } Application.Top.Add(window); Application.Run(window); }
public static string TestSerializedRequest <T>(IReadOnlyCollection <JsonConverter> converters, T module, string method, params string[] parameters) where T : class, IModule { IJsonRpcService service = BuildRpcService(module); JsonRpcRequest request = GetJsonRequest(method, parameters); JsonRpcResponse response = service.SendRequestAsync(request).Result; var serializer = new EthereumJsonSerializer(); foreach (var converter in converters) { serializer.RegisterConverter(converter); } var serialized = serializer.Serialize(response); TestContext.Out?.WriteLine("Serialized:"); TestContext.Out?.WriteLine(serialized); return(serialized); }
public void Init(string path) { var dbOnTheRocks = new ConsumerSessionsRocksDb(path, new DbConfig(), LimboLogs.Instance); var consumerSessionsBytes = dbOnTheRocks.GetAll(); var consumerSessionsDecoder = new ConsumerSessionDecoder(); var consumerSessions = consumerSessionsBytes .Select(b => consumerSessionsDecoder.Decode(b.Value.AsRlpStream())); var window = new Window("Consumer sessions") { X = 0, Y = 10, Width = Dim.Fill(), Height = Dim.Fill() }; if (!consumerSessions.Any()) { MessageBox.Query(40, 7, "Consumer sessions", "No data." + $"{Environment.NewLine}(ESC to close)"); window.FocusPrev(); return; } var y = 1; foreach (var consumerSession in consumerSessions) { var consumerSessionBtn = new Button(1, y++, $"DepositId: {consumerSession.DepositId}," + $"ConsumerAddress: {consumerSession.ConsumerAddress}"); consumerSessionBtn.Clicked = () => { var consumerSessionDetailsWindow = new Window("Session details") { X = 0, Y = 10, Width = Dim.Fill(), Height = Dim.Fill() }; Application.Top.Add(consumerSessionDetailsWindow); var serializer = new EthereumJsonSerializer(); var consumerSessionLbl = new Label(1, 1, serializer.Serialize(consumerSession, true)); consumerSessionDetailsWindow.Add(consumerSessionLbl); Application.Run(consumerSessionDetailsWindow); }; window.Add(consumerSessionBtn); } Application.Top.Add(window); Application.Run(window); }
public void Init(string path) { var dbOnTheRocks = new ProviderReceiptsRocksDb(path, new DbConfig(), LimboLogs.Instance); var receiptsBytes = dbOnTheRocks.GetAll(); var receiptDecoder = new DataDeliveryReceiptDetailsDecoder(); var receipts = receiptsBytes .Select(b => receiptDecoder.Decode(b.Value.AsRlpStream())); var window = new Window("Provider receipts") { X = 0, Y = 10, Width = Dim.Fill(), Height = Dim.Fill() }; if (!receipts.Any()) { MessageBox.Query(40, 7, "Provider receipts", "No data." + $"{Environment.NewLine}(ESC to close)"); window.FocusPrev(); return; } var y = 1; foreach (var receipt in receipts) { var receiptBtn = new Button(1, y++, $"Id: {receipt.Id}, DepositId: {receipt.DepositId}"); receiptBtn.Clicked = () => { var receiptDetailsWindow = new Window("Receipt details") { X = 0, Y = 10, Width = Dim.Fill(), Height = Dim.Fill() }; Application.Top.Add(receiptDetailsWindow); var serializer = new EthereumJsonSerializer(); var receiptLbl = new Label(1, 1, serializer.Serialize(receipt, true)); receiptDetailsWindow.Add(receiptLbl); Application.Run(receiptDetailsWindow); }; window.Add(receiptBtn); } Application.Top.Add(window); Application.Run(window); }
public void Ed25519_precompile_can_verify_correct_sig() { HashProvider hashProvider = new HashProvider(HashingAlgorithm.GetAlgorithmMetadata("blake2b-256")); FfiWrapper cryptoContext = new FfiWrapper(); IPrivateKey signingPrivateKey = cryptoContext.GeneratePrivateKey(); var signingPublicKeyBytes = signingPrivateKey.GetPublicKey().Bytes; var byteCode = PrepareEd25519PrecompileCall(hashProvider, cryptoContext, signingPrivateKey, signingPrivateKey); GethLikeTxTracer txTracer = RunVirtualMachine(byteCode); EthereumJsonSerializer serializer = new EthereumJsonSerializer(); GethLikeTxTrace trace = txTracer.BuildResult(); TestContext.WriteLine(serializer.Serialize(trace, true)); trace.Entries.Last().Stack.First().Should().Be("0000000000000000000000000000000000000000000000000000000000000001"); trace.Entries.Last().Memory.First().Should().StartWith("01"); }
public void Get_transaction_by_hash(bool includeHeader) { Keccak txHash = TestItem.KeccakA; JsonRpcSuccessResponse response = new JsonRpcSuccessResponse { Id = "id1", Result = "result" }; _jsonRpcClient.Post <object>("proof_getTransactionByHash", txHash, includeHeader) .Returns(_serializer.Serialize(response)); JsValue value = _engine.Execute($"proof.getTransactionByHash(\"{txHash}\", {(includeHeader ? "true" : "false")})"); Colorful.Console.WriteLine(_serializer.Serialize(value.ToObject(), true)); Assert.AreNotEqual(JsValue.Null, value); }
public void Ed25519_precompile_can_report_too_long_input() { var byteCode = Bytes.FromHexString( // PUSH1 32 PUSH1 0 PUSH1 192 PUSH1 0 PUSH20 address GAS STATICCALL // make a call to precompile and pass invalid [0,192) bytes of memory as an input // and store result at [0,1) of memory array // allow precompile to use all the gas required "6001600060c0600073" + GetEd25519PrecompileAddressAsHex() + "45fa00"); GethLikeTxTracer txTracer = RunVirtualMachine(byteCode); EthereumJsonSerializer serializer = new EthereumJsonSerializer(); GethLikeTxTrace trace = txTracer.BuildResult(); TestContext.WriteLine(serializer.Serialize(trace, true)); trace.Entries.Last().Stack.First().Should().Be("0000000000000000000000000000000000000000000000000000000000000000"); }
public void R_and_s_are_quantity_and_not_data() { byte[] r = new byte[32]; byte[] s = new byte[32]; r[1] = 1; s[2] = 2; Transaction tx = new Transaction(); tx.Signature = new Signature(r, s, 27); TransactionForRpc txForRpc = new TransactionForRpc(tx); EthereumJsonSerializer serializer = new EthereumJsonSerializer(); string serialized = serializer.Serialize(txForRpc); serialized.Should().Contain("0x20000000000000000000000000000000000000000000000000000000000"); serialized.Should().Contain("0x1000000000000000000000000000000000000000000000000000000000000"); Console.WriteLine(serialized); }
protected void TestRoundtrip <T>(T item, Func <T, T, bool> equalityComparer, JsonConverter <T> converter = null, string description = null) { EthereumJsonSerializer serializer = BuildSerializer(); if (converter != null) { serializer.RegisterConverter(converter); } string result = serializer.Serialize(item); T deserialized = serializer.Deserialize <T>(result); if (equalityComparer == null) { Assert.AreEqual(item, deserialized, description); } else { Assert.True(equalityComparer(item, deserialized), description); } }
private void TestCallWithStorageAndCode(byte[] code, UInt256 gasPrice, Address from = null) { StateProvider stateProvider = CreateInitialState(code); StorageProvider storageProvider = new StorageProvider(new TrieStore(_dbProvider.StateDb, LimboLogs.Instance), stateProvider, LimboLogs.Instance); for (int i = 0; i < 10000; i++) { storageProvider.Set(new StorageCell(TestItem.AddressB, (UInt256)i), i.ToBigEndianByteArray()); } storageProvider.Commit(); storageProvider.CommitTrees(0); stateProvider.Commit(MainnetSpecProvider.Instance.GenesisSpec, null); stateProvider.CommitTree(0); Keccak root = stateProvider.StateRoot; Block block = Build.A.Block.WithParent(_blockTree.Head).WithStateRoot(root).TestObject; BlockTreeBuilder.AddBlock(_blockTree, block); Block blockOnTop = Build.A.Block.WithParent(block).WithStateRoot(root).TestObject; BlockTreeBuilder.AddBlock(_blockTree, blockOnTop); // would need to setup state root somehow... TransactionForRpc tx = new TransactionForRpc { // we are testing system transaction here when From is null From = from, To = TestItem.AddressB, GasPrice = gasPrice, Nonce = 1000 }; CallResultWithProof callResultWithProof = _proofModule.proof_call(tx, new BlockParameter(blockOnTop.Number)).Data; Assert.Greater(callResultWithProof.Accounts.Length, 0); // just the keys for debugging Span <byte> span = stackalloc byte[32]; new UInt256(0).ToBigEndian(span); Keccak k0 = Keccak.Compute(span); // just the keys for debugging new UInt256(1).ToBigEndian(span); Keccak k1 = Keccak.Compute(span); // just the keys for debugging new UInt256(2).ToBigEndian(span); Keccak k2 = Keccak.Compute(span); foreach (AccountProof accountProof in callResultWithProof.Accounts) { // this is here for diagnostics - so you can read what happens in the test // generally the account here should be consistent with the values inside the proof // the exception will be thrown if the account did not exist before the call Account account; try { account = new AccountDecoder().Decode(new RlpStream(ProofVerifier.Verify(accountProof.Proof, block.StateRoot))); } catch (Exception) { // ignored } foreach (StorageProof storageProof in accountProof.StorageProofs) { // we read the values here just to allow easier debugging so you can confirm that the value is same as the one in the proof and in the trie byte[] value = ProofVerifier.Verify(storageProof.Proof, accountProof.StorageRoot); } } EthereumJsonSerializer serializer = new EthereumJsonSerializer(); string response = RpcTest.TestSerializedRequest(_proofModule, "proof_call", $"{serializer.Serialize(tx)}", $"{blockOnTop.Number}"); Assert.True(response.Contains("\"result\"")); }