-
Notifications
You must be signed in to change notification settings - Fork 16
/
marshal.go
388 lines (354 loc) · 11.4 KB
/
marshal.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
package marshal
import (
"bytes"
"encoding/hex"
"errors"
"fmt"
"github.com/Qitmeer/qng/common/hash"
"github.com/Qitmeer/qng/consensus/vm"
"github.com/Qitmeer/qng/core/blockchain/opreturn"
"github.com/Qitmeer/qng/core/json"
"github.com/Qitmeer/qng/core/protocol"
"github.com/Qitmeer/qng/core/types"
"github.com/Qitmeer/qng/engine/txscript"
"github.com/Qitmeer/qng/meerdag"
"github.com/Qitmeer/qng/meerevm/common"
"github.com/Qitmeer/qng/params"
"strconv"
"time"
)
// messageToHex serializes a message to the wire protocol encoding using the
// latest protocol version and returns a hex-encoded string of the result.
func MessageToHex(tx *types.Transaction) (string, error) {
var buf bytes.Buffer
err := tx.Encode(&buf, protocol.ProtocolVersion, types.TxSerializeFull)
if err != nil {
context := fmt.Sprintf("Failed to encode msg of type %T", tx)
return "", fmt.Errorf("%s : %s", context, err.Error())
}
return hex.EncodeToString(buf.Bytes()), nil
}
func MarshalJsonTx(tx *types.Tx, params *params.Params, blkHashStr string,
confirmations int64, coinbaseAmout types.AmountMap, state bool) (json.TxRawResult, error) {
if tx == nil {
return json.TxRawResult{}, errors.New("can't marshal nil transaction")
}
return MarshalJsonTransaction(tx, params, blkHashStr, confirmations, coinbaseAmout, state)
}
func MarshalJsonTransaction(transaction *types.Tx, params *params.Params, blkHashStr string,
confirmations int64, coinbaseAmout types.AmountMap, state bool) (json.TxRawResult, error) {
tx := transaction.Tx
hexStr, err := MessageToHex(tx)
if err != nil {
return json.TxRawResult{}, err
}
txr := json.TxRawResult{
Hex: hexStr,
Txid: tx.TxHash().String(),
TxHash: tx.TxHashFull().String(),
Size: int32(tx.SerializeSize()),
Version: tx.Version,
LockTime: tx.LockTime,
Expire: tx.Expire,
Vin: MarshJsonVin(tx),
Duplicate: transaction.IsDuplicate,
Txsvalid: state,
Type: types.DetermineTxType(tx).String(),
}
if tx.Timestamp.Unix() > 0 {
txr.Timestamp = tx.Timestamp.Format(time.RFC3339)
}
if tx.IsCoinBase() {
txr.Vout = MarshJsonCoinbaseVout(tx, nil, params, coinbaseAmout)
} else {
txr.Vout = MarshJsonVout(tx, nil, params)
}
if blkHashStr != "" {
txr.BlockHash = blkHashStr
txr.Confirmations = confirmations
}
return txr, nil
}
func MarshJsonVin(tx *types.Transaction) []json.Vin {
// Coinbase transactions only have a single txin by definition.
vinList := make([]json.Vin, len(tx.TxIn))
if tx.IsCoinBase() {
txIn := tx.TxIn[0]
vinEntry := &vinList[0]
vinEntry.Coinbase = hex.EncodeToString(txIn.SignScript)
vinEntry.Sequence = txIn.Sequence
return vinList
} else if types.IsTokenTx(tx) {
for i, txIn := range tx.TxIn {
disbuf, _ := txscript.DisasmString(txIn.SignScript)
vinEntry := &vinList[i]
if i == 0 {
vinEntry.TxType = types.DetermineTxType(tx).String()
} else {
vinEntry.Txid = txIn.PreviousOut.Hash.String()
vinEntry.Vout = txIn.PreviousOut.OutIndex
vinEntry.Sequence = txIn.Sequence
}
vinEntry.ScriptSig = &json.ScriptSig{
Asm: disbuf,
Hex: hex.EncodeToString(txIn.SignScript),
}
}
return vinList
} else if types.IsCrossChainImportTx(tx) {
ctx, err := vm.NewImportTx(tx)
if err != nil {
return vinList
}
from, err := common.NewMeerEVMAddress(ctx.From)
if err != nil {
return vinList
}
vinEntry := &vinList[0]
vinEntry.From = from.String()
vinEntry.Value = ctx.Value
vinEntry.TxType = types.DetermineTxType(tx).String()
return vinList
} else if types.IsCrossChainVMTx(tx) {
vinList[0].TxType = types.DetermineTxType(tx).String()
sig := tx.TxIn[0].SignScript
// disbuf, _ := txscript.DisasmString(sig) //TODO, the Disasm is not fully work for the cross-chain tx
vinList[0].ScriptSig = &json.ScriptSig{
// Asm: disbuf,
Hex: common.ToTxHexStr(sig),
}
vinList[0].Txid = "0x" + tx.TxIn[0].PreviousOut.Hash.String()
return vinList
}
for i, txIn := range tx.TxIn {
// The disassembled string will contain [error] inline
// if the script doesn't fully parse, so ignore the
// error here.
disbuf, _ := txscript.DisasmString(txIn.SignScript)
vinEntry := &vinList[i]
vinEntry.Txid = txIn.PreviousOut.Hash.String()
vinEntry.Vout = txIn.PreviousOut.OutIndex
vinEntry.Sequence = txIn.Sequence
vinEntry.ScriptSig = &json.ScriptSig{
Asm: disbuf,
Hex: hex.EncodeToString(txIn.SignScript),
}
}
return vinList
}
func MarshJsonVout(tx *types.Transaction, filterAddrMap map[string]struct{}, params *params.Params) []json.Vout {
voutList := make([]json.Vout, 0, len(tx.TxOut))
for _, v := range tx.TxOut {
// The disassembled string will contain [error] inline if the
// script doesn't fully parse, so ignore the error here.
disbuf, _ := txscript.DisasmString(v.PkScript)
// Ignore the error here since an error means the script
// couldn't parse and there is no additional information
// about it anyways.
sc, addrs, reqSigs, _ := txscript.ExtractPkScriptAddrs(
v.PkScript, params)
scriptClass := sc.String()
// Encode the addresses while checking if the address passes the
// filter when needed.
passesFilter := len(filterAddrMap) == 0
encodedAddrs := make([]string, len(addrs))
for j, addr := range addrs {
encodedAddr := addr.String()
encodedAddrs[j] = encodedAddr
// No need to check the map again if the filter already
// passes.
if passesFilter {
continue
}
if _, exists := filterAddrMap[encodedAddr]; exists {
passesFilter = true
}
}
if !passesFilter {
continue
}
var vout json.Vout
vout.Coin = v.Amount.Id.Name()
vout.CoinId = uint16(v.Amount.Id)
vout.Amount = uint64(v.Amount.Value)
voutSPK := &vout.ScriptPubKey
voutSPK.Addresses = encodedAddrs
if len(encodedAddrs) > 0 {
if types.CoinID(vout.CoinId) == types.MEERB {
ctx, err := vm.NewExportTx(tx)
if err == nil {
to, err := common.NewMeerEVMAddress(ctx.To)
if err == nil {
vout.To = to.String()
voutList = append(voutList, vout)
continue
}
}
}
}
voutSPK.Asm = disbuf
voutSPK.Type = scriptClass
voutSPK.ReqSigs = int32(reqSigs)
voutSPK.Hex = hex.EncodeToString(v.PkScript)
voutList = append(voutList, vout)
}
return voutList
}
func MarshJsonCoinbaseVout(tx *types.Transaction, filterAddrMap map[string]struct{}, params *params.Params, coinbaseAmout types.AmountMap) []json.Vout {
if len(coinbaseAmout) <= 0 ||
tx.CachedTxHash().IsEqual(params.GenesisBlock.Transactions[0].CachedTxHash()) {
return MarshJsonVout(tx, filterAddrMap, params)
}
voutList := make([]json.Vout, 0, len(tx.TxOut))
for k, v := range tx.TxOut {
isopr := opreturn.IsOPReturn(v.PkScript)
if k > 0 && coinbaseAmout[v.Amount.Id] <= 0 && !isopr {
continue
}
// The disassembled string will contain [error] inline if the
// script doesn't fully parse, so ignore the error here.
disbuf, _ := txscript.DisasmString(v.PkScript)
// Ignore the error here since an error means the script
// couldn't parse and there is no additional information
// about it anyways.
sc, addrs, reqSigs, _ := txscript.ExtractPkScriptAddrs(
v.PkScript, params)
scriptClass := sc.String()
// Encode the addresses while checking if the address passes the
// filter when needed.
passesFilter := len(filterAddrMap) == 0
encodedAddrs := make([]string, len(addrs))
for j, addr := range addrs {
encodedAddr := addr.String()
encodedAddrs[j] = encodedAddr
// No need to check the map again if the filter already
// passes.
if passesFilter {
continue
}
if _, exists := filterAddrMap[encodedAddr]; exists {
passesFilter = true
}
}
if !passesFilter {
continue
}
var vout json.Vout
voutSPK := &vout.ScriptPubKey
if !isopr {
vout.Coin = v.Amount.Id.Name()
vout.CoinId = uint16(v.Amount.Id)
vout.Amount = uint64(coinbaseAmout[v.Amount.Id])
voutSPK.Type = scriptClass
} else {
opr, err := opreturn.NewOPReturnFrom(v.PkScript)
if err != nil {
continue
}
voutSPK.Type = opr.GetType().Name()
}
voutSPK.Addresses = encodedAddrs
voutSPK.Asm = disbuf
voutSPK.Hex = hex.EncodeToString(v.PkScript)
voutSPK.ReqSigs = int32(reqSigs)
voutList = append(voutList, vout)
}
return voutList
}
// RPCMarshalBlock converts the given block to the RPC output which depends on fullTx. If inclTx is true transactions are
// returned. When fullTx is true the returned block contains full transaction details, otherwise it will only contain
// transaction hashes.
func MarshalJsonBlock(b *types.SerializedBlock, inclTx bool, fullTx bool,
params *params.Params, confirmations int64, children []*hash.Hash, state bool, isOrdered bool, coinbaseAmout types.AmountMap, coinbaseFee types.AmountMap) (json.OrderedResult, error) {
head := b.Block().Header // copies the header once
// Get next block hash unless there are none.
fields := json.OrderedResult{
{Key: "hash", Val: b.Hash().String()},
{Key: "txsvalid", Val: state},
{Key: "confirmations", Val: confirmations},
{Key: "version", Val: head.Version},
{Key: "weight", Val: types.GetBlockWeight(b.Block())},
{Key: "height", Val: b.Height()},
{Key: "txRoot", Val: head.TxRoot.String()},
}
if isOrdered {
fields = append(fields, json.KV{Key: "order", Val: b.Order()})
}
if inclTx {
formatTx := func(tx *types.Tx) (interface{}, error) {
return tx.Hash().String(), nil
}
if fullTx {
formatTx = func(tx *types.Tx) (interface{}, error) {
return MarshalJsonTx(tx, params, b.Hash().String(), confirmations, coinbaseAmout, state)
}
}
txs := b.Transactions()
transactions := make([]interface{}, len(txs))
var err error
for i, tx := range txs {
if transactions[i], err = formatTx(tx); err != nil {
return nil, err
}
}
fields = append(fields, json.KV{Key: "transactions", Val: transactions})
}
if coinbaseFee != nil {
fees := []json.Amout{}
for coinid, amount := range coinbaseFee {
if amount <= 0 {
continue
}
fees = append(fees, json.Amout{CoinId: uint16(coinid), Amount: amount})
}
if len(fees) > 0 {
fields = append(fields, json.KV{Key: "transactionfee", Val: fees})
}
}
fields = append(fields, json.OrderedResult{
{Key: "stateRoot", Val: head.StateRoot.String()},
{Key: "bits", Val: strconv.FormatUint(uint64(head.Difficulty), 16)},
{Key: "difficulty", Val: head.Difficulty},
{Key: "pow", Val: head.Pow.GetPowResult()},
{Key: "timestamp", Val: head.Timestamp.Format(time.RFC3339)},
{Key: "parentroot", Val: head.ParentRoot.String()},
}...)
tempArr := []string{}
if b.Block().Parents != nil && len(b.Block().Parents) > 0 {
for i := 0; i < len(b.Block().Parents); i++ {
tempArr = append(tempArr, b.Block().Parents[i].String())
}
} else {
tempArr = append(tempArr, "null")
}
fields = append(fields, json.KV{Key: "parents", Val: tempArr})
tempArr = []string{}
if len(children) > 0 {
for i := 0; i < len(children); i++ {
tempArr = append(tempArr, children[i].String())
}
} else {
tempArr = append(tempArr, "null")
}
fields = append(fields, json.KV{Key: "children", Val: tempArr})
return fields, nil
}
func GetGraphStateResult(gs *meerdag.GraphState) *json.GetGraphStateResult {
if gs != nil {
tips := []string{}
for k, v := range gs.GetTipsList() {
if k == 0 {
tips = append(tips, v.String()+" main")
} else {
tips = append(tips, v.String())
}
}
return &json.GetGraphStateResult{
Tips: tips,
MainOrder: uint32(gs.GetMainOrder()),
Layer: uint32(gs.GetLayer()),
MainHeight: uint32(gs.GetMainHeight()),
}
}
return nil
}