|
1 | 1 | using System; |
2 | 2 | using System.Buffers; |
3 | 3 | using System.Buffers.Binary; |
4 | | -using System.Diagnostics; |
5 | 4 | using System.IO; |
6 | 5 | using System.Text; |
| 6 | +using MessagePack; |
| 7 | +using MessagePack.Formatters; |
7 | 8 | using Neo.IO.Json; |
8 | 9 | using Neo.Network.RPC; |
9 | 10 | using Neo.Network.RPC.Models; |
@@ -75,45 +76,32 @@ public UInt256 GetBlockHash(uint index) |
75 | 76 | return UInt256.Parse(json.AsString()); |
76 | 77 | } |
77 | 78 |
|
| 79 | + static readonly IMessagePackFormatter<byte[]?> byteArrayFormatter = |
| 80 | + MessagePackSerializerOptions.Standard.Resolver.GetFormatter<byte[]?>(); |
| 81 | + |
78 | 82 | public byte[]? GetState(UInt256 rootHash, UInt160 scriptHash, ReadOnlyMemory<byte> key) |
79 | 83 | { |
80 | 84 | var familyName = $"{nameof(GetState)}{rootHash}{scriptHash}"; |
81 | 85 | var family = db.GetOrCreateColumnFamily(familyName); |
82 | | - var value = db.Get(key.Span, family); |
| 86 | + var cachedState = db.Get(key.Span, family); |
83 | 87 |
|
84 | | - JObject jsonValue; |
85 | | - if (value != null) |
| 88 | + if (cachedState != null) |
86 | 89 | { |
87 | | - jsonValue = JObject.Parse(value); |
| 90 | + var reader = new MessagePackReader(cachedState); |
| 91 | + return byteArrayFormatter.Deserialize(ref reader, MessagePackSerializerOptions.Standard); |
88 | 92 | } |
89 | 93 | else |
90 | 94 | { |
91 | | - try |
92 | | - { |
93 | | - jsonValue = rpcClient.RpcSend("getstate", |
94 | | - rootHash.ToString(), |
95 | | - scriptHash.ToString(), |
96 | | - Convert.ToBase64String(key.Span)); |
97 | | - } |
98 | | - catch (RpcException ex) |
99 | | - { |
100 | | - if (ex.HResult == RpcClientExtensions.COR_E_KEYNOTFOUND) |
101 | | - { |
102 | | - jsonValue = JObject.Null; |
103 | | - } |
104 | | - else |
105 | | - { |
106 | | - throw; |
107 | | - } |
108 | | - } |
109 | | - var jsonBytes = jsonValue == null |
110 | | - ? Neo.Utility.StrictUTF8.GetBytes("null") |
111 | | - : jsonValue.ToByteArray(false); |
112 | | - db.Put(key.Span, jsonBytes, family); |
113 | | - } |
| 95 | + var state = rpcClient.GetState(rootHash, scriptHash, key.Span); |
| 96 | + |
| 97 | + var buffer = new ArrayBufferWriter<byte>(); |
| 98 | + var writer = new MessagePackWriter(buffer); |
| 99 | + writer.Write(state); |
| 100 | + writer.Flush(); |
| 101 | + db.Put(key.Span, buffer.WrittenSpan, family); |
114 | 102 |
|
115 | | - return jsonValue == null || jsonValue == JObject.Null ? null |
116 | | - : Convert.FromBase64String(jsonValue.AsString()); |
| 103 | + return state; |
| 104 | + } |
117 | 105 | } |
118 | 106 |
|
119 | 107 | public RpcStateRoot GetStateRoot(uint index) |
|
0 commit comments