1// Copyright (c) 2014-2017 The btcsuite developers
2// Use of this source code is governed by an ISC
3// license that can be found in the LICENSE file.
4
5package btcjson
6
7import "encoding/json"
8
9// GetBlockHeaderVerboseResult models the data from the getblockheader command when
10// the verbose flag is set.  When the verbose flag is not set, getblockheader
11// returns a hex-encoded string.
12type GetBlockHeaderVerboseResult struct {
13	Hash          string  `json:"hash"`
14	Confirmations int64   `json:"confirmations"`
15	Height        int32   `json:"height"`
16	Version       int32   `json:"version"`
17	VersionHex    string  `json:"versionHex"`
18	MerkleRoot    string  `json:"merkleroot"`
19	Time          int64   `json:"time"`
20	Nonce         uint64  `json:"nonce"`
21	Bits          string  `json:"bits"`
22	Difficulty    float64 `json:"difficulty"`
23	PreviousHash  string  `json:"previousblockhash,omitempty"`
24	NextHash      string  `json:"nextblockhash,omitempty"`
25}
26
27// GetBlockVerboseResult models the data from the getblock command when the
28// verbose flag is set.  When the verbose flag is not set, getblock returns a
29// hex-encoded string.
30type GetBlockVerboseResult struct {
31	Hash          string        `json:"hash"`
32	Confirmations int64         `json:"confirmations"`
33	StrippedSize  int32         `json:"strippedsize"`
34	Size          int32         `json:"size"`
35	Weight        int32         `json:"weight"`
36	Height        int64         `json:"height"`
37	Version       int32         `json:"version"`
38	VersionHex    string        `json:"versionHex"`
39	MerkleRoot    string        `json:"merkleroot"`
40	Tx            []string      `json:"tx,omitempty"`
41	RawTx         []TxRawResult `json:"rawtx,omitempty"`
42	Time          int64         `json:"time"`
43	Nonce         uint32        `json:"nonce"`
44	Bits          string        `json:"bits"`
45	Difficulty    float64       `json:"difficulty"`
46	PreviousHash  string        `json:"previousblockhash"`
47	NextHash      string        `json:"nextblockhash,omitempty"`
48}
49
50// CreateMultiSigResult models the data returned from the createmultisig
51// command.
52type CreateMultiSigResult struct {
53	Address      string `json:"address"`
54	RedeemScript string `json:"redeemScript"`
55}
56
57// DecodeScriptResult models the data returned from the decodescript command.
58type DecodeScriptResult struct {
59	Asm       string   `json:"asm"`
60	ReqSigs   int32    `json:"reqSigs,omitempty"`
61	Type      string   `json:"type"`
62	Addresses []string `json:"addresses,omitempty"`
63	P2sh      string   `json:"p2sh,omitempty"`
64}
65
66// GetAddedNodeInfoResultAddr models the data of the addresses portion of the
67// getaddednodeinfo command.
68type GetAddedNodeInfoResultAddr struct {
69	Address   string `json:"address"`
70	Connected string `json:"connected"`
71}
72
73// GetAddedNodeInfoResult models the data from the getaddednodeinfo command.
74type GetAddedNodeInfoResult struct {
75	AddedNode string                        `json:"addednode"`
76	Connected *bool                         `json:"connected,omitempty"`
77	Addresses *[]GetAddedNodeInfoResultAddr `json:"addresses,omitempty"`
78}
79
80// SoftForkDescription describes the current state of a soft-fork which was
81// deployed using a super-majority block signalling.
82type SoftForkDescription struct {
83	ID      string `json:"id"`
84	Version uint32 `json:"version"`
85	Reject  struct {
86		Status bool `json:"status"`
87	} `json:"reject"`
88}
89
90// Bip9SoftForkDescription describes the current state of a defined BIP0009
91// version bits soft-fork.
92type Bip9SoftForkDescription struct {
93	Status     string `json:"status"`
94	Bit        uint8  `json:"bit"`
95	StartTime1 int64  `json:"startTime"`
96	StartTime2 int64  `json:"start_time"`
97	Timeout    int64  `json:"timeout"`
98	Since      int32  `json:"since"`
99}
100
101// StartTime returns the starting time of the softfork as a Unix epoch.
102func (d *Bip9SoftForkDescription) StartTime() int64 {
103	if d.StartTime1 != 0 {
104		return d.StartTime1
105	}
106	return d.StartTime2
107}
108
109// SoftForks describes the current softforks enabled by the backend. Softforks
110// activated through BIP9 are grouped together separate from any other softforks
111// with different activation types.
112type SoftForks struct {
113	SoftForks     []*SoftForkDescription              `json:"softforks"`
114	Bip9SoftForks map[string]*Bip9SoftForkDescription `json:"bip9_softforks"`
115}
116
117// UnifiedSoftForks describes a softforks in a general manner, irrespective of
118// its activation type. This was a format introduced by bitcoind v0.19.0
119type UnifiedSoftFork struct {
120	Type                    string                   `json:"type"`
121	BIP9SoftForkDescription *Bip9SoftForkDescription `json:"bip9"`
122	Height                  int32                    `json:"height"`
123	Active                  bool                     `json:"active"`
124}
125
126// UnifiedSoftForks describes the current softforks enabled the by the backend
127// in a unified manner, i.e, softforks with different activation types are
128// grouped together. This was a format introduced by bitcoind v0.19.0
129type UnifiedSoftForks struct {
130	SoftForks map[string]*UnifiedSoftFork `json:"softforks"`
131}
132
133// GetBlockChainInfoResult models the data returned from the getblockchaininfo
134// command.
135type GetBlockChainInfoResult struct {
136	Chain                string  `json:"chain"`
137	Blocks               int32   `json:"blocks"`
138	Headers              int32   `json:"headers"`
139	BestBlockHash        string  `json:"bestblockhash"`
140	Difficulty           float64 `json:"difficulty"`
141	MedianTime           int64   `json:"mediantime"`
142	VerificationProgress float64 `json:"verificationprogress,omitempty"`
143	Pruned               bool    `json:"pruned"`
144	PruneHeight          int32   `json:"pruneheight,omitempty"`
145	ChainWork            string  `json:"chainwork,omitempty"`
146	*SoftForks
147	*UnifiedSoftForks
148}
149
150// GetBlockTemplateResultTx models the transactions field of the
151// getblocktemplate command.
152type GetBlockTemplateResultTx struct {
153	Data    string  `json:"data"`
154	Hash    string  `json:"hash"`
155	Depends []int64 `json:"depends"`
156	Fee     int64   `json:"fee"`
157	SigOps  int64   `json:"sigops"`
158	Weight  int64   `json:"weight"`
159}
160
161// GetBlockTemplateResultAux models the coinbaseaux field of the
162// getblocktemplate command.
163type GetBlockTemplateResultAux struct {
164	Flags string `json:"flags"`
165}
166
167// GetBlockTemplateResult models the data returned from the getblocktemplate
168// command.
169type GetBlockTemplateResult struct {
170	// Base fields from BIP 0022.  CoinbaseAux is optional.  One of
171	// CoinbaseTxn or CoinbaseValue must be specified, but not both.
172	Bits          string                     `json:"bits"`
173	CurTime       int64                      `json:"curtime"`
174	Height        int64                      `json:"height"`
175	PreviousHash  string                     `json:"previousblockhash"`
176	SigOpLimit    int64                      `json:"sigoplimit,omitempty"`
177	SizeLimit     int64                      `json:"sizelimit,omitempty"`
178	WeightLimit   int64                      `json:"weightlimit,omitempty"`
179	Transactions  []GetBlockTemplateResultTx `json:"transactions"`
180	Version       int32                      `json:"version"`
181	CoinbaseAux   *GetBlockTemplateResultAux `json:"coinbaseaux,omitempty"`
182	CoinbaseTxn   *GetBlockTemplateResultTx  `json:"coinbasetxn,omitempty"`
183	CoinbaseValue *int64                     `json:"coinbasevalue,omitempty"`
184	WorkID        string                     `json:"workid,omitempty"`
185
186	// Witness commitment defined in BIP 0141.
187	DefaultWitnessCommitment string `json:"default_witness_commitment,omitempty"`
188
189	// Optional long polling from BIP 0022.
190	LongPollID  string `json:"longpollid,omitempty"`
191	LongPollURI string `json:"longpolluri,omitempty"`
192	SubmitOld   *bool  `json:"submitold,omitempty"`
193
194	// Basic pool extension from BIP 0023.
195	Target  string `json:"target,omitempty"`
196	Expires int64  `json:"expires,omitempty"`
197
198	// Mutations from BIP 0023.
199	MaxTime    int64    `json:"maxtime,omitempty"`
200	MinTime    int64    `json:"mintime,omitempty"`
201	Mutable    []string `json:"mutable,omitempty"`
202	NonceRange string   `json:"noncerange,omitempty"`
203
204	// Block proposal from BIP 0023.
205	Capabilities  []string `json:"capabilities,omitempty"`
206	RejectReasion string   `json:"reject-reason,omitempty"`
207}
208
209// GetMempoolEntryResult models the data returned from the getmempoolentry
210// command.
211type GetMempoolEntryResult struct {
212	Size             int32    `json:"size"`
213	Fee              float64  `json:"fee"`
214	ModifiedFee      float64  `json:"modifiedfee"`
215	Time             int64    `json:"time"`
216	Height           int64    `json:"height"`
217	StartingPriority float64  `json:"startingpriority"`
218	CurrentPriority  float64  `json:"currentpriority"`
219	DescendantCount  int64    `json:"descendantcount"`
220	DescendantSize   int64    `json:"descendantsize"`
221	DescendantFees   float64  `json:"descendantfees"`
222	AncestorCount    int64    `json:"ancestorcount"`
223	AncestorSize     int64    `json:"ancestorsize"`
224	AncestorFees     float64  `json:"ancestorfees"`
225	Depends          []string `json:"depends"`
226}
227
228// GetMempoolInfoResult models the data returned from the getmempoolinfo
229// command.
230type GetMempoolInfoResult struct {
231	Size  int64 `json:"size"`
232	Bytes int64 `json:"bytes"`
233}
234
235// NetworksResult models the networks data from the getnetworkinfo command.
236type NetworksResult struct {
237	Name                      string `json:"name"`
238	Limited                   bool   `json:"limited"`
239	Reachable                 bool   `json:"reachable"`
240	Proxy                     string `json:"proxy"`
241	ProxyRandomizeCredentials bool   `json:"proxy_randomize_credentials"`
242}
243
244// LocalAddressesResult models the localaddresses data from the getnetworkinfo
245// command.
246type LocalAddressesResult struct {
247	Address string `json:"address"`
248	Port    uint16 `json:"port"`
249	Score   int32  `json:"score"`
250}
251
252// GetNetworkInfoResult models the data returned from the getnetworkinfo
253// command.
254type GetNetworkInfoResult struct {
255	Version         int32                  `json:"version"`
256	SubVersion      string                 `json:"subversion"`
257	ProtocolVersion int32                  `json:"protocolversion"`
258	LocalServices   string                 `json:"localservices"`
259	LocalRelay      bool                   `json:"localrelay"`
260	TimeOffset      int64                  `json:"timeoffset"`
261	Connections     int32                  `json:"connections"`
262	NetworkActive   bool                   `json:"networkactive"`
263	Networks        []NetworksResult       `json:"networks"`
264	RelayFee        float64                `json:"relayfee"`
265	IncrementalFee  float64                `json:"incrementalfee"`
266	LocalAddresses  []LocalAddressesResult `json:"localaddresses"`
267	Warnings        string                 `json:"warnings"`
268}
269
270// GetPeerInfoResult models the data returned from the getpeerinfo command.
271type GetPeerInfoResult struct {
272	ID             int32   `json:"id"`
273	Addr           string  `json:"addr"`
274	AddrLocal      string  `json:"addrlocal,omitempty"`
275	Services       string  `json:"services"`
276	RelayTxes      bool    `json:"relaytxes"`
277	LastSend       int64   `json:"lastsend"`
278	LastRecv       int64   `json:"lastrecv"`
279	BytesSent      uint64  `json:"bytessent"`
280	BytesRecv      uint64  `json:"bytesrecv"`
281	ConnTime       int64   `json:"conntime"`
282	TimeOffset     int64   `json:"timeoffset"`
283	PingTime       float64 `json:"pingtime"`
284	PingWait       float64 `json:"pingwait,omitempty"`
285	Version        uint32  `json:"version"`
286	SubVer         string  `json:"subver"`
287	Inbound        bool    `json:"inbound"`
288	StartingHeight int32   `json:"startingheight"`
289	CurrentHeight  int32   `json:"currentheight,omitempty"`
290	BanScore       int32   `json:"banscore"`
291	FeeFilter      int64   `json:"feefilter"`
292	SyncNode       bool    `json:"syncnode"`
293}
294
295// GetRawMempoolVerboseResult models the data returned from the getrawmempool
296// command when the verbose flag is set.  When the verbose flag is not set,
297// getrawmempool returns an array of transaction hashes.
298type GetRawMempoolVerboseResult struct {
299	Size             int32    `json:"size"`
300	Vsize            int32    `json:"vsize"`
301	Weight           int32    `json:"weight"`
302	Fee              float64  `json:"fee"`
303	Time             int64    `json:"time"`
304	Height           int64    `json:"height"`
305	StartingPriority float64  `json:"startingpriority"`
306	CurrentPriority  float64  `json:"currentpriority"`
307	Depends          []string `json:"depends"`
308}
309
310// ScriptPubKeyResult models the scriptPubKey data of a tx script.  It is
311// defined separately since it is used by multiple commands.
312type ScriptPubKeyResult struct {
313	Asm       string   `json:"asm"`
314	Hex       string   `json:"hex,omitempty"`
315	ReqSigs   int32    `json:"reqSigs,omitempty"`
316	Type      string   `json:"type"`
317	Addresses []string `json:"addresses,omitempty"`
318}
319
320// GetTxOutResult models the data from the gettxout command.
321type GetTxOutResult struct {
322	BestBlock     string             `json:"bestblock"`
323	Confirmations int64              `json:"confirmations"`
324	Value         float64            `json:"value"`
325	ScriptPubKey  ScriptPubKeyResult `json:"scriptPubKey"`
326	Coinbase      bool               `json:"coinbase"`
327}
328
329// GetNetTotalsResult models the data returned from the getnettotals command.
330type GetNetTotalsResult struct {
331	TotalBytesRecv uint64 `json:"totalbytesrecv"`
332	TotalBytesSent uint64 `json:"totalbytessent"`
333	TimeMillis     int64  `json:"timemillis"`
334}
335
336// ScriptSig models a signature script.  It is defined separately since it only
337// applies to non-coinbase.  Therefore the field in the Vin structure needs
338// to be a pointer.
339type ScriptSig struct {
340	Asm string `json:"asm"`
341	Hex string `json:"hex"`
342}
343
344// Vin models parts of the tx data.  It is defined separately since
345// getrawtransaction, decoderawtransaction, and searchrawtransaction use the
346// same structure.
347type Vin struct {
348	Coinbase  string     `json:"coinbase"`
349	Txid      string     `json:"txid"`
350	Vout      uint32     `json:"vout"`
351	ScriptSig *ScriptSig `json:"scriptSig"`
352	Sequence  uint32     `json:"sequence"`
353	Witness   []string   `json:"txinwitness"`
354}
355
356// IsCoinBase returns a bool to show if a Vin is a Coinbase one or not.
357func (v *Vin) IsCoinBase() bool {
358	return len(v.Coinbase) > 0
359}
360
361// HasWitness returns a bool to show if a Vin has any witness data associated
362// with it or not.
363func (v *Vin) HasWitness() bool {
364	return len(v.Witness) > 0
365}
366
367// MarshalJSON provides a custom Marshal method for Vin.
368func (v *Vin) MarshalJSON() ([]byte, error) {
369	if v.IsCoinBase() {
370		coinbaseStruct := struct {
371			Coinbase string   `json:"coinbase"`
372			Sequence uint32   `json:"sequence"`
373			Witness  []string `json:"witness,omitempty"`
374		}{
375			Coinbase: v.Coinbase,
376			Sequence: v.Sequence,
377			Witness:  v.Witness,
378		}
379		return json.Marshal(coinbaseStruct)
380	}
381
382	if v.HasWitness() {
383		txStruct := struct {
384			Txid      string     `json:"txid"`
385			Vout      uint32     `json:"vout"`
386			ScriptSig *ScriptSig `json:"scriptSig"`
387			Witness   []string   `json:"txinwitness"`
388			Sequence  uint32     `json:"sequence"`
389		}{
390			Txid:      v.Txid,
391			Vout:      v.Vout,
392			ScriptSig: v.ScriptSig,
393			Witness:   v.Witness,
394			Sequence:  v.Sequence,
395		}
396		return json.Marshal(txStruct)
397	}
398
399	txStruct := struct {
400		Txid      string     `json:"txid"`
401		Vout      uint32     `json:"vout"`
402		ScriptSig *ScriptSig `json:"scriptSig"`
403		Sequence  uint32     `json:"sequence"`
404	}{
405		Txid:      v.Txid,
406		Vout:      v.Vout,
407		ScriptSig: v.ScriptSig,
408		Sequence:  v.Sequence,
409	}
410	return json.Marshal(txStruct)
411}
412
413// PrevOut represents previous output for an input Vin.
414type PrevOut struct {
415	Addresses []string `json:"addresses,omitempty"`
416	Value     float64  `json:"value"`
417}
418
419// VinPrevOut is like Vin except it includes PrevOut.  It is used by searchrawtransaction
420type VinPrevOut struct {
421	Coinbase  string     `json:"coinbase"`
422	Txid      string     `json:"txid"`
423	Vout      uint32     `json:"vout"`
424	ScriptSig *ScriptSig `json:"scriptSig"`
425	Witness   []string   `json:"txinwitness"`
426	PrevOut   *PrevOut   `json:"prevOut"`
427	Sequence  uint32     `json:"sequence"`
428}
429
430// IsCoinBase returns a bool to show if a Vin is a Coinbase one or not.
431func (v *VinPrevOut) IsCoinBase() bool {
432	return len(v.Coinbase) > 0
433}
434
435// HasWitness returns a bool to show if a Vin has any witness data associated
436// with it or not.
437func (v *VinPrevOut) HasWitness() bool {
438	return len(v.Witness) > 0
439}
440
441// MarshalJSON provides a custom Marshal method for VinPrevOut.
442func (v *VinPrevOut) MarshalJSON() ([]byte, error) {
443	if v.IsCoinBase() {
444		coinbaseStruct := struct {
445			Coinbase string `json:"coinbase"`
446			Sequence uint32 `json:"sequence"`
447		}{
448			Coinbase: v.Coinbase,
449			Sequence: v.Sequence,
450		}
451		return json.Marshal(coinbaseStruct)
452	}
453
454	if v.HasWitness() {
455		txStruct := struct {
456			Txid      string     `json:"txid"`
457			Vout      uint32     `json:"vout"`
458			ScriptSig *ScriptSig `json:"scriptSig"`
459			Witness   []string   `json:"txinwitness"`
460			PrevOut   *PrevOut   `json:"prevOut,omitempty"`
461			Sequence  uint32     `json:"sequence"`
462		}{
463			Txid:      v.Txid,
464			Vout:      v.Vout,
465			ScriptSig: v.ScriptSig,
466			Witness:   v.Witness,
467			PrevOut:   v.PrevOut,
468			Sequence:  v.Sequence,
469		}
470		return json.Marshal(txStruct)
471	}
472
473	txStruct := struct {
474		Txid      string     `json:"txid"`
475		Vout      uint32     `json:"vout"`
476		ScriptSig *ScriptSig `json:"scriptSig"`
477		PrevOut   *PrevOut   `json:"prevOut,omitempty"`
478		Sequence  uint32     `json:"sequence"`
479	}{
480		Txid:      v.Txid,
481		Vout:      v.Vout,
482		ScriptSig: v.ScriptSig,
483		PrevOut:   v.PrevOut,
484		Sequence:  v.Sequence,
485	}
486	return json.Marshal(txStruct)
487}
488
489// Vout models parts of the tx data.  It is defined separately since both
490// getrawtransaction and decoderawtransaction use the same structure.
491type Vout struct {
492	Value        float64            `json:"value"`
493	N            uint32             `json:"n"`
494	ScriptPubKey ScriptPubKeyResult `json:"scriptPubKey"`
495}
496
497// GetMiningInfoResult models the data from the getmininginfo command.
498type GetMiningInfoResult struct {
499	Blocks             int64   `json:"blocks"`
500	CurrentBlockSize   uint64  `json:"currentblocksize"`
501	CurrentBlockWeight uint64  `json:"currentblockweight"`
502	CurrentBlockTx     uint64  `json:"currentblocktx"`
503	Difficulty         float64 `json:"difficulty"`
504	Errors             string  `json:"errors"`
505	Generate           bool    `json:"generate"`
506	GenProcLimit       int32   `json:"genproclimit"`
507	HashesPerSec       int64   `json:"hashespersec"`
508	NetworkHashPS      int64   `json:"networkhashps"`
509	PooledTx           uint64  `json:"pooledtx"`
510	TestNet            bool    `json:"testnet"`
511}
512
513// GetWorkResult models the data from the getwork command.
514type GetWorkResult struct {
515	Data     string `json:"data"`
516	Hash1    string `json:"hash1"`
517	Midstate string `json:"midstate"`
518	Target   string `json:"target"`
519}
520
521// InfoChainResult models the data returned by the chain server getinfo command.
522type InfoChainResult struct {
523	Version         int32   `json:"version"`
524	ProtocolVersion int32   `json:"protocolversion"`
525	Blocks          int32   `json:"blocks"`
526	TimeOffset      int64   `json:"timeoffset"`
527	Connections     int32   `json:"connections"`
528	Proxy           string  `json:"proxy"`
529	Difficulty      float64 `json:"difficulty"`
530	TestNet         bool    `json:"testnet"`
531	RelayFee        float64 `json:"relayfee"`
532	Errors          string  `json:"errors"`
533}
534
535// TxRawResult models the data from the getrawtransaction command.
536type TxRawResult struct {
537	Hex           string `json:"hex"`
538	Txid          string `json:"txid"`
539	Hash          string `json:"hash,omitempty"`
540	Size          int32  `json:"size,omitempty"`
541	Vsize         int32  `json:"vsize,omitempty"`
542	Weight        int32  `json:"weight,omitempty"`
543	Version       int32  `json:"version"`
544	LockTime      uint32 `json:"locktime"`
545	Vin           []Vin  `json:"vin"`
546	Vout          []Vout `json:"vout"`
547	BlockHash     string `json:"blockhash,omitempty"`
548	Confirmations uint64 `json:"confirmations,omitempty"`
549	Time          int64  `json:"time,omitempty"`
550	Blocktime     int64  `json:"blocktime,omitempty"`
551}
552
553// SearchRawTransactionsResult models the data from the searchrawtransaction
554// command.
555type SearchRawTransactionsResult struct {
556	Hex           string       `json:"hex,omitempty"`
557	Txid          string       `json:"txid"`
558	Hash          string       `json:"hash"`
559	Size          string       `json:"size"`
560	Vsize         string       `json:"vsize"`
561	Weight        string       `json:"weight"`
562	Version       int32        `json:"version"`
563	LockTime      uint32       `json:"locktime"`
564	Vin           []VinPrevOut `json:"vin"`
565	Vout          []Vout       `json:"vout"`
566	BlockHash     string       `json:"blockhash,omitempty"`
567	Confirmations uint64       `json:"confirmations,omitempty"`
568	Time          int64        `json:"time,omitempty"`
569	Blocktime     int64        `json:"blocktime,omitempty"`
570}
571
572// TxRawDecodeResult models the data from the decoderawtransaction command.
573type TxRawDecodeResult struct {
574	Txid     string `json:"txid"`
575	Version  int32  `json:"version"`
576	Locktime uint32 `json:"locktime"`
577	Vin      []Vin  `json:"vin"`
578	Vout     []Vout `json:"vout"`
579}
580
581// ValidateAddressChainResult models the data returned by the chain server
582// validateaddress command.
583type ValidateAddressChainResult struct {
584	IsValid bool   `json:"isvalid"`
585	Address string `json:"address,omitempty"`
586}
587