forked from gcash/bchd
/
server.go
3530 lines (3122 loc) · 112 KB
/
server.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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package bchrpc
import (
"bytes"
"context"
"encoding/hex"
"errors"
"fmt"
"io"
"math/big"
"net/http"
"strconv"
"sync"
"sync/atomic"
"time"
"github.com/gcash/bchd/bchrpc/pb"
"github.com/gcash/bchd/blockchain"
"github.com/gcash/bchd/blockchain/indexers"
"github.com/gcash/bchd/chaincfg"
"github.com/gcash/bchd/chaincfg/chainhash"
"github.com/gcash/bchd/database"
"github.com/gcash/bchd/mempool"
"github.com/gcash/bchd/mining"
"github.com/gcash/bchd/txscript"
"github.com/gcash/bchd/wire"
"github.com/gcash/bchutil"
"github.com/gcash/bchutil/merkleblock"
"github.com/simpleledgerinc/goslp"
"github.com/simpleledgerinc/goslp/v1parser"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/reflection"
"google.golang.org/grpc/status"
)
// maxAddressQuerySize is the max number of addresses
// to return per query.
const maxAddressQuerySize = 10000
var serviceMap = map[string]interface{}{
"pb.bchrpc": &GrpcServer{},
"grpc.reflection.v1alpha.ServerReflection": &reflectionServer{},
}
type reflectionServer struct{}
func (s *reflectionServer) checkReady() bool {
return true
}
// ServiceReady returns nil when the service is ready and a gRPC error when not.
func ServiceReady(service string) error {
s, ok := serviceMap[service]
if !ok {
return status.Errorf(codes.Unimplemented, "service %s not found", service)
}
type readyChecker interface {
checkReady() bool
}
ready := true
r, ok := s.(readyChecker)
if ok {
ready = r.checkReady()
}
if !ready {
return status.Errorf(codes.FailedPrecondition, "service %v is not ready", service)
}
return nil
}
// NetManager is an interface which provides functions for handling new transactions.
// This is used by the SubmitTransaction RPC to notify the rest of the system a new
// transaction needs to be handled.
type NetManager interface {
// AddRebroadcastInventory adds 'iv' to the list of inventories to be
// rebroadcasted at random intervals until they show up in a block.
AddRebroadcastInventory(iv *wire.InvVect, data interface{})
// AnnounceNewTransactions generates and relays inventory vectors and notifies
// both websocket and getblocktemplate long poll clients of the passed
// transactions. This function should be called whenever new transactions
// are added to the mempool.
AnnounceNewTransactions(txns []*mempool.TxDesc)
}
// GrpcServerConfig hols the various objects needed by the GrpcServer to
// perform its functions.
type GrpcServerConfig struct {
Server *grpc.Server
HTTPServer *http.Server
TimeSource blockchain.MedianTimeSource
Chain *blockchain.BlockChain
ChainParams *chaincfg.Params
DB database.DB
TxMemPool *mempool.TxPool
NetMgr NetManager
TxIndex *indexers.TxIndex
AddrIndex *indexers.AddrIndex
CfIndex *indexers.CfIndex
SlpIndex *indexers.SlpIndex
}
// GrpcServer is the gRPC server implementation. It holds all the objects
// necessary to serve the RPCs and implements the bchrpc.proto interface.
type GrpcServer struct {
timeSource blockchain.MedianTimeSource
chain *blockchain.BlockChain
chainParams *chaincfg.Params
db database.DB
txMemPool *mempool.TxPool
netMgr NetManager
txIndex *indexers.TxIndex
addrIndex *indexers.AddrIndex
cfIndex *indexers.CfIndex
slpIndex *indexers.SlpIndex
httpServer *http.Server
subscribe chan *rpcEventSubscription
events chan interface{}
quit chan struct{}
wg sync.WaitGroup
ready uint32 // atomic
shutdown int32 // atomic
}
// NewGrpcServer returns a new GrpcServer which has not yet
// be started.
func NewGrpcServer(cfg *GrpcServerConfig) *GrpcServer {
s := &GrpcServer{
timeSource: cfg.TimeSource,
chain: cfg.Chain,
chainParams: cfg.ChainParams,
db: cfg.DB,
txMemPool: cfg.TxMemPool,
netMgr: cfg.NetMgr,
txIndex: cfg.TxIndex,
addrIndex: cfg.AddrIndex,
cfIndex: cfg.CfIndex,
slpIndex: cfg.SlpIndex,
httpServer: cfg.HTTPServer,
subscribe: make(chan *rpcEventSubscription),
events: make(chan interface{}),
quit: make(chan struct{}),
wg: sync.WaitGroup{},
}
reflection.Register(cfg.Server)
pb.RegisterBchrpcServer(cfg.Server, s)
serviceMap["pb.bchrpc"] = s
// listen to changes in the mempool for adding/removing from slp entry cache
go s.slpEventHandler()
return s
}
// rpcEventTxAccepted indicates a new tx was accepted into the mempool.
type rpcEventTxAccepted struct {
*mempool.TxDesc
}
// rpcEventBlockConnected indicates a new block connected to the current best
// chain.
type rpcEventBlockConnected struct {
*bchutil.Block
}
// rpcEventBlockDisconnected indicates a block that was disconnected from the
// current best chain.
type rpcEventBlockDisconnected struct {
*bchutil.Block
}
// rpcEventSubscription represents a subscription to events from the RPC server.
type rpcEventSubscription struct {
in chan interface{} // rpc events to be put by the dispatcher
out chan interface{} // rpc events to be read by the client
unsubscribe chan struct{} // close to unsubscribe
}
// Events returns the channel clients listen to to get new events.
func (s *rpcEventSubscription) Events() <-chan interface{} {
return s.out
}
// Unsubscribe is to be called by the client to stop the subscription.
func (s *rpcEventSubscription) Unsubscribe() {
close(s.unsubscribe)
}
// subscribeEvents returns a new subscription to all the events the RPC server
// receives.
func (s *GrpcServer) subscribeEvents() *rpcEventSubscription {
sub := &rpcEventSubscription{
in: make(chan interface{}),
out: make(chan interface{}),
unsubscribe: make(chan struct{}),
}
// Start a queue handler for the subscription so that slow connections don't
// hold up faster ones.
s.wg.Add(1)
go func() {
queueHandler(sub.in, sub.out, s.quit)
s.wg.Done()
}()
select {
case s.subscribe <- sub:
case <-s.quit:
}
return sub
}
// runEventDispatcher runs a process that will forward new incoming events to
// all the currently active client processes.
//
// It should be run in a goroutine and calls Done on the wait group on finish.
func (s *GrpcServer) runEventDispatcher() {
defer s.wg.Done()
subscriptions := make(map[*rpcEventSubscription]struct{})
for {
select {
case newSub := <-s.subscribe:
subscriptions[newSub] = struct{}{}
case event := <-s.events:
// Dispatch to all clients.
for sub := range subscriptions {
select {
case sub.in <- event:
case <-sub.unsubscribe:
// If client unsubscribed, just delete it.
delete(subscriptions, sub)
}
}
case <-s.quit:
for sub := range subscriptions {
close(sub.in)
}
return
}
}
}
// dispatchEvent dispatches an event and makes sure it doesn't block when the
// server is shutting down.
func (s *GrpcServer) dispatchEvent(event interface{}) {
select {
case s.events <- event:
case <-s.quit:
}
}
// NotifyNewTransactions is called by the server when new transactions
// are accepted in the mempool.
func (s *GrpcServer) NotifyNewTransactions(txs []*mempool.TxDesc) {
for _, txDesc := range txs {
s.dispatchEvent(&rpcEventTxAccepted{txDesc})
}
}
// handleBlockchainNotification handles the callback from the blockchain package
// that notifies the RPC server about changes in the chain.
func (s *GrpcServer) handleBlockchainNotification(notification *blockchain.Notification) {
switch notification.Type {
case blockchain.NTBlockConnected:
block, ok := notification.Data.(*bchutil.Block)
if !ok {
log.Warnf("Chain connected notification is not a block.")
break
}
s.dispatchEvent(&rpcEventBlockConnected{block})
case blockchain.NTBlockDisconnected:
block, ok := notification.Data.(*bchutil.Block)
if !ok {
log.Warnf("Chain disconnected notification is not a block.")
break
}
s.dispatchEvent(&rpcEventBlockDisconnected{block})
}
}
// Start will start the GrpcServer, subscribe to blockchain notifications
// and start the EventDispatcher in a new goroutine.
func (s *GrpcServer) Start() {
if atomic.SwapUint32(&s.ready, 1) != 0 {
panic("service already started")
}
s.wg.Add(1)
s.chain.Subscribe(s.handleBlockchainNotification)
go s.runEventDispatcher()
}
// Stop is used by server.go to stop the gRPC listener.
func (s *GrpcServer) Stop() error {
if atomic.AddInt32(&s.shutdown, 1) != 1 {
log.Infof("gRPC server is already in the process of shutting down")
return nil
}
log.Warnf("gRPC server shutting down")
err := s.httpServer.Close()
if err != nil {
log.Errorf("Problem shutting down grpc: %v", err)
return err
}
close(s.quit)
s.wg.Wait()
log.Infof("gRPC server shutdown complete")
return nil
}
// checkReady returns if the server is ready to serve data.
func (s *GrpcServer) checkReady() bool {
return atomic.LoadUint32(&s.ready) != 0
}
// GetMempoolInfo returns the state of the current mempool.
func (s *GrpcServer) GetMempoolInfo(ctx context.Context, req *pb.GetMempoolInfoRequest) (*pb.GetMempoolInfoResponse, error) {
nBytes := uint32(0)
for _, txDesc := range s.txMemPool.TxDescs() {
nBytes += uint32(txDesc.Tx.MsgTx().SerializeSize())
}
resp := &pb.GetMempoolInfoResponse{
Size: uint32(s.txMemPool.Count()),
Bytes: nBytes,
}
return resp, nil
}
// GetMempool returns information about all of the transactions currently in the memory pool.
// Offers an option to return full transactions or just transactions hashes.
func (s *GrpcServer) GetMempool(ctx context.Context, req *pb.GetMempoolRequest) (*pb.GetMempoolResponse, error) {
rawMempool := s.txMemPool.MiningDescs()
resp := &pb.GetMempoolResponse{}
for _, txDesc := range rawMempool {
if req.FullTransactions {
respTx := marshalTransaction(txDesc.Tx, 0, nil, 0, s)
stxos, err := s.txMemPool.FetchInputUtxos(txDesc.Tx)
if err != nil {
continue
}
for i, in := range txDesc.Tx.MsgTx().TxIn {
entry := stxos.LookupEntry(in.PreviousOutPoint)
if entry != nil {
respTx.Inputs[i].Value = entry.Amount()
respTx.Inputs[i].PreviousScript = entry.PkScript()
_, addrs, _, err := txscript.ExtractPkScriptAddrs(entry.PkScript(), s.chainParams)
if err == nil && len(addrs) > 0 {
respTx.Inputs[i].Address = addrs[0].String()
}
}
}
resp.TransactionData = append(resp.TransactionData, &pb.GetMempoolResponse_TransactionData{
TxidsOrTxs: &pb.GetMempoolResponse_TransactionData_Transaction{
Transaction: respTx,
},
})
} else {
resp.TransactionData = append(resp.TransactionData, &pb.GetMempoolResponse_TransactionData{
TxidsOrTxs: &pb.GetMempoolResponse_TransactionData_TransactionHash{
TransactionHash: txDesc.Tx.Hash().CloneBytes(),
},
})
}
}
return resp, nil
}
// GetBlockchainInfo returns info about the blockchain including the most recent
// block hash and height.
func (s *GrpcServer) GetBlockchainInfo(ctx context.Context, req *pb.GetBlockchainInfoRequest) (*pb.GetBlockchainInfoResponse, error) {
bestSnapShot := s.chain.BestSnapshot()
var net pb.GetBlockchainInfoResponse_BitcoinNet
switch s.chainParams {
case &chaincfg.MainNetParams:
net = pb.GetBlockchainInfoResponse_MAINNET
case &chaincfg.TestNet3Params:
net = pb.GetBlockchainInfoResponse_TESTNET3
case &chaincfg.RegressionNetParams:
net = pb.GetBlockchainInfoResponse_REGTEST
case &chaincfg.SimNetParams:
net = pb.GetBlockchainInfoResponse_SIMNET
default:
return nil, status.Error(codes.Internal, "unknown network parameters")
}
gsEnabled := false
if s.slpIndex != nil {
gsEnabled = s.slpIndex.GraphSearchEnabled()
}
resp := &pb.GetBlockchainInfoResponse{
AddrIndex: s.addrIndex != nil,
TxIndex: s.txIndex != nil,
SlpIndex: s.slpIndex != nil,
SlpGraphsearch: gsEnabled,
BestHeight: bestSnapShot.Height,
BestBlockHash: bestSnapShot.Hash[:],
BitcoinNet: net,
Difficulty: getDifficultyRatio(bestSnapShot.Bits, s.chainParams),
MedianTime: bestSnapShot.MedianTime.Unix(),
}
return resp, nil
}
// GetBlockInfo returns metadata and info for a specified block.
func (s *GrpcServer) GetBlockInfo(ctx context.Context, req *pb.GetBlockInfoRequest) (*pb.GetBlockInfoResponse, error) {
var (
block *bchutil.Block
err error
)
if len(req.GetHash()) == 0 {
block, err = s.chain.BlockByHeight(req.GetHeight())
} else {
h, err := chainhash.NewHash(req.GetHash())
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "invalid hash: %v", err)
}
block, err = s.chain.BlockByHash(h)
}
if err != nil || block == nil {
return nil, status.Error(codes.NotFound, "block not found")
}
medianTime, err := s.chain.MedianTimeByHash(block.Hash())
if err != nil {
return nil, status.Error(codes.Internal, "error calculating median time for block")
}
resp := &pb.GetBlockInfoResponse{
Info: marshalBlockInfo(block, s.chain.BestSnapshot().Height-block.Height()+1, medianTime, s.chainParams),
}
nextHeader, err := s.chain.HeaderByHeight(block.Height() + 1)
if err == nil {
nextHash := nextHeader.BlockHash()
resp.Info.NextBlockHash = nextHash.CloneBytes()
}
return resp, nil
}
// GetBlock returns detailed data for a block.
func (s *GrpcServer) GetBlock(ctx context.Context, req *pb.GetBlockRequest) (*pb.GetBlockResponse, error) {
var (
block *bchutil.Block
err error
)
if len(req.GetHash()) == 0 {
block, err = s.chain.BlockByHeight(req.GetHeight())
} else {
h, err := chainhash.NewHash(req.GetHash())
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "invalid hash: %v", err)
}
block, err = s.chain.BlockByHash(h)
}
if err != nil || block == nil {
return nil, status.Error(codes.NotFound, "block not found")
}
confirmations := s.chain.BestSnapshot().Height - block.Height() + 1
medianTime, err := s.chain.MedianTimeByHash(block.Hash())
if err != nil {
return nil, status.Error(codes.Internal, "error calculating median time for block")
}
resp := &pb.GetBlockResponse{
Block: &pb.Block{
Info: marshalBlockInfo(block, confirmations, medianTime, s.chainParams),
},
}
nextHeader, err := s.chain.HeaderByHeight(block.Height() + 1)
if err == nil {
nextHash := nextHeader.BlockHash()
resp.Block.Info.NextBlockHash = nextHash.CloneBytes()
}
var spentTxos []blockchain.SpentTxOut
if req.FullTransactions {
spentTxos, err = s.chain.FetchSpendJournal(block)
if err != nil {
return nil, status.Error(codes.Internal, "error loading spend journal")
}
}
spendIdx := 0
for idx, tx := range block.Transactions() {
if req.FullTransactions {
header := block.MsgBlock().Header
respTx := marshalTransaction(tx, confirmations, &header, block.Height(), s)
for i := range tx.MsgTx().TxIn {
if idx > 0 {
stxo := spentTxos[spendIdx]
respTx.Inputs[i].Value = stxo.Amount
respTx.Inputs[i].PreviousScript = stxo.PkScript
_, addrs, _, err := txscript.ExtractPkScriptAddrs(stxo.PkScript, s.chainParams)
if err == nil && len(addrs) > 0 {
respTx.Inputs[i].Address = addrs[0].String()
s.setInputSlpTokenAddress(respTx.Inputs[i], addrs[0])
}
spendIdx++
}
}
resp.Block.TransactionData = append(resp.Block.TransactionData, &pb.Block_TransactionData{
TxidsOrTxs: &pb.Block_TransactionData_Transaction{
Transaction: respTx,
},
})
} else {
resp.Block.TransactionData = append(resp.Block.TransactionData, &pb.Block_TransactionData{
TxidsOrTxs: &pb.Block_TransactionData_TransactionHash{
TransactionHash: tx.Hash().CloneBytes(),
},
})
}
}
return resp, nil
}
// GetRawBlock returns a block in a serialized format.
func (s *GrpcServer) GetRawBlock(ctx context.Context, req *pb.GetRawBlockRequest) (*pb.GetRawBlockResponse, error) {
var (
block *bchutil.Block
err error
)
if len(req.GetHash()) == 0 {
block, err = s.chain.BlockByHeight(req.GetHeight())
} else {
h, err := chainhash.NewHash(req.GetHash())
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "invalid hash: %v", err)
}
block, err = s.chain.BlockByHash(h)
}
if err != nil || block == nil {
return nil, status.Error(codes.NotFound, "block not found")
}
var buf bytes.Buffer
if err := block.MsgBlock().BchEncode(&buf, wire.ProtocolVersion, wire.BaseEncoding); err != nil {
return nil, status.Error(codes.Internal, "block serialization error")
}
resp := &pb.GetRawBlockResponse{
Block: buf.Bytes(),
}
return resp, nil
}
// GetBlockFilter returns the compact filter (cf) of a block as a Golomb-Rice encoded set.
//
// **Requires CfIndex**
func (s *GrpcServer) GetBlockFilter(ctx context.Context, req *pb.GetBlockFilterRequest) (*pb.GetBlockFilterResponse, error) {
if s.cfIndex == nil {
return nil, status.Error(codes.Unavailable, "cfindex required")
}
var (
blockHash *chainhash.Hash
err error
)
if len(req.GetHash()) == 0 {
blockHash, err = s.chain.BlockHashByHeight(req.GetHeight())
if err != nil {
return nil, status.Errorf(codes.NotFound, "block not found at height %d", req.GetHeight())
}
} else {
blockHash, err = chainhash.NewHash(req.GetHash())
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "invalid hash: %v", err)
}
}
filter, err := s.cfIndex.FilterByBlockHash(blockHash, wire.GCSFilterRegular)
if err != nil {
return nil, status.Error(codes.NotFound, "filter not found")
}
resp := &pb.GetBlockFilterResponse{
Filter: filter,
}
return resp, nil
}
// GetHeaders takes a block locator object and returns a batch of no more than 2000
// headers. Upon parsing the block locator, if the server concludes there has been a
// fork, it will send headers starting at the fork point, or genesis if no blocks in
// the locator are in the best chain. If the locator is already at the tip no headers
// will be returned.
// see: bchd/bchrpc/documentation/wallet_operation.md
func (s *GrpcServer) GetHeaders(ctx context.Context, req *pb.GetHeadersRequest) (*pb.GetHeadersResponse, error) {
var (
locator blockchain.BlockLocator
err error
)
for _, b := range req.BlockLocatorHashes {
blockHash, err := chainhash.NewHash(b)
if err != nil {
return nil, status.Error(codes.InvalidArgument, "invalid locator hash")
}
locator = append(locator, blockHash)
}
var stopHash chainhash.Hash
if len(req.StopHash) > 0 {
hash, err := chainhash.NewHash(req.StopHash)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "invalid stop hash %v", err)
}
stopHash = *hash
}
headers := s.chain.LocateHeaders(locator, &stopHash)
resp := &pb.GetHeadersResponse{}
var startHeight int32
if len(headers) > 0 {
startHash := headers[0].BlockHash()
startHeight, err = s.chain.BlockHeightByHash(&startHash)
if err != nil {
return nil, status.Error(codes.Internal, "error loading start header height")
}
}
bestHeight := s.chain.BestSnapshot().Height
for i, header := range headers {
hash := header.BlockHash()
resp.Headers = append(resp.Headers, &pb.BlockInfo{
Difficulty: getDifficultyRatio(header.Bits, s.chainParams),
Hash: hash.CloneBytes(),
Height: startHeight + int32(i),
Version: header.Version,
Timestamp: header.Timestamp.Unix(),
MerkleRoot: header.MerkleRoot.CloneBytes(),
Nonce: header.Nonce,
Bits: header.Bits,
PreviousBlock: header.PrevBlock.CloneBytes(),
Confirmations: bestHeight - (startHeight + int32(i)) + 1,
})
}
return resp, nil
}
// GetTransaction returns a transaction given its hash.
//
// **Requires TxIndex**
// **Requires SlpIndex for all token metadata
func (s *GrpcServer) GetTransaction(ctx context.Context, req *pb.GetTransactionRequest) (*pb.GetTransactionResponse, error) {
if s.txIndex == nil {
return nil, status.Error(codes.Unavailable, "txindex required")
}
if req.IncludeTokenMetadata && s.slpIndex == nil {
return nil, status.Error(codes.Unavailable, "slpindex required")
}
txHash, err := chainhash.NewHash(req.Hash)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "invalid transaction hash %v", err)
}
if txDesc, err := s.txMemPool.FetchTxDesc(txHash); err == nil {
tx := marshalTransaction(txDesc.Tx, 0, nil, 0, s)
tx.Timestamp = txDesc.Added.Unix()
view, err := s.txMemPool.FetchInputUtxos(txDesc.Tx)
if err == nil {
for i, in := range txDesc.Tx.MsgTx().TxIn {
stxo := view.LookupEntry(in.PreviousOutPoint)
if stxo != nil {
tx.Inputs[i].Value = stxo.Amount()
tx.Inputs[i].PreviousScript = stxo.PkScript()
_, addrs, _, err := txscript.ExtractPkScriptAddrs(stxo.PkScript(), s.chainParams)
if err == nil && len(addrs) > 0 {
tx.Inputs[i].Address = addrs[0].String()
s.setInputSlpTokenAddress(tx.Inputs[i], addrs[0])
}
}
}
}
var tokenMetadata *pb.SlpTokenMetadata
if req.IncludeTokenMetadata && tx.SlpTransactionInfo.ValidityJudgement == pb.SlpTransactionInfo_VALID {
tokenID, err := chainhash.NewHash(tx.SlpTransactionInfo.TokenId)
if err != nil {
return nil, status.Errorf(codes.Internal, "an unknown problem occurred when parsing token id: %s: %v", hex.EncodeToString(tx.SlpTransactionInfo.TokenId), err)
}
tokenMetadata, err = s.marshalTokenMetadata(*tokenID)
if err != nil {
msg := fmt.Sprintf("an unknown problem occurred when building token metadata for token id %s: %v", hex.EncodeToString(tx.SlpTransactionInfo.TokenId), err)
log.Criticalf(msg)
return nil, status.Errorf(codes.Internal, msg)
}
}
resp := &pb.GetTransactionResponse{
Transaction: tx,
TokenMetadata: tokenMetadata,
}
return resp, nil
}
txBytes, blockHeight, blockHash, err := s.fetchTransactionFromBlock(txHash)
if err != nil {
return nil, err
}
// Deserialize the transaction
var msgTx wire.MsgTx
err = msgTx.Deserialize(bytes.NewReader(txBytes))
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to deserialize transaction: %v", err)
}
header, err := s.chain.HeaderByHash(blockHash)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to load block header %v", err)
}
respTx := marshalTransaction(bchutil.NewTx(&msgTx), s.chain.BestSnapshot().Height-blockHeight+1, &header, blockHeight, s)
if s.txIndex != nil {
if err := s.setInputMetadata(respTx); err != nil {
return nil, err
}
}
var tokenMetadata *pb.SlpTokenMetadata
if req.IncludeTokenMetadata && respTx.SlpTransactionInfo.ValidityJudgement == pb.SlpTransactionInfo_VALID {
tokenID, err := chainhash.NewHash(respTx.SlpTransactionInfo.TokenId)
if err != nil {
return nil, status.Errorf(codes.Internal, "an unknown problem occurred when parsing token id %s: %v", hex.EncodeToString(respTx.SlpTransactionInfo.TokenId), err)
}
tokenMetadata, err = s.marshalTokenMetadata(*tokenID)
if err != nil {
msg := fmt.Sprintf("an unknown problem occurred when building token metadata for token id %s: %v", hex.EncodeToString(respTx.SlpTransactionInfo.TokenId), err)
log.Criticalf(msg)
return nil, status.Errorf(codes.Internal, msg)
}
}
resp := &pb.GetTransactionResponse{
Transaction: respTx,
TokenMetadata: tokenMetadata,
}
return resp, nil
}
// GetRawTransaction returns a serialized transaction given a transaction hash.
//
// **Requires TxIndex**
func (s *GrpcServer) GetRawTransaction(ctx context.Context, req *pb.GetRawTransactionRequest) (*pb.GetRawTransactionResponse, error) {
if s.txIndex == nil {
return nil, status.Error(codes.Unavailable, "txindex required")
}
txHash, err := chainhash.NewHash(req.Hash)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "invalid transaction hash: %v", err)
}
if tx, err := s.txMemPool.FetchTransaction(txHash); err == nil {
var buf bytes.Buffer
if err := tx.MsgTx().BchEncode(&buf, wire.ProtocolVersion, wire.BaseEncoding); err != nil {
return nil, status.Error(codes.Internal, "error serializing transaction")
}
resp := &pb.GetRawTransactionResponse{
Transaction: buf.Bytes(),
}
return resp, nil
}
txBytes, _, _, err := s.fetchTransactionFromBlock(txHash)
if err != nil {
return nil, err
}
resp := &pb.GetRawTransactionResponse{
Transaction: txBytes,
}
return resp, nil
}
// GetAddressTransactions returns the transactions for the given address. Offers offset,
// limit, and from block options.
//
// **Requires AddressIndex**
func (s *GrpcServer) GetAddressTransactions(ctx context.Context, req *pb.GetAddressTransactionsRequest) (*pb.GetAddressTransactionsResponse, error) {
if s.addrIndex == nil {
return nil, status.Error(codes.Unavailable, "addrindex required")
}
if req.NbFetch > maxAddressQuerySize {
return nil, status.Errorf(codes.InvalidArgument, "nbfetch exceeds max of %d", maxAddressQuerySize)
}
// Attempt to decode the supplied address.
addr, err := bchutil.DecodeAddress(req.Address, s.chainParams)
if err != nil {
return nil, status.Error(codes.InvalidArgument, "invalid address")
}
// use cash address format
addr, err = bchutil.ConvertSlpToCashAddress(addr, s.chainParams)
if err != nil {
return nil, status.Error(codes.Internal, "couldn't convert address to cash address format")
}
startHeight := int32(0)
if len(req.GetHash()) == 0 {
startHeight = req.GetHeight()
} else {
h, err := chainhash.NewHash(req.GetHash())
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "invalid hash: %v", err)
}
// If error here we'll just use the genesis
startHeight, _ = s.chain.BlockHeightByHash(h)
}
confirmedTxs, err := s.fetchTransactionsByAddress(addr, startHeight, int(req.NbFetch), int(req.NbSkip))
if err != nil {
return nil, err
}
resp := &pb.GetAddressTransactionsResponse{}
tip := s.chain.BestSnapshot().Height
for _, cTx := range confirmedTxs {
tx := marshalTransaction(bchutil.NewTx(&cTx.tx), tip-cTx.blockHeight+1, cTx.blockHeader, cTx.blockHeight, s)
if s.txIndex != nil {
if err := s.setInputMetadata(tx); err != nil {
return nil, err
}
}
resp.ConfirmedTransactions = append(resp.ConfirmedTransactions, tx)
}
unconfirmedTxs := s.addrIndex.UnconfirmedTxnsForAddress(addr)
for _, uTx := range unconfirmedTxs {
tx := marshalTransaction(uTx, 0, nil, 0, s)
txDesc, err := s.txMemPool.FetchTxDesc(uTx.Hash())
if err != nil {
continue
}
view, err := s.txMemPool.FetchInputUtxos(txDesc.Tx)
if err == nil {
for i, in := range txDesc.Tx.MsgTx().TxIn {
stxo := view.LookupEntry(in.PreviousOutPoint)
if stxo != nil {
tx.Inputs[i].Value = stxo.Amount()
tx.Inputs[i].PreviousScript = stxo.PkScript()
_, addrs, _, err := txscript.ExtractPkScriptAddrs(stxo.PkScript(), s.chainParams)
if err == nil && len(addrs) > 0 {
tx.Inputs[i].Address = addrs[0].String()
s.setInputSlpTokenAddress(tx.Inputs[i], addrs[0])
}
}
}
}
mempoolTx := &pb.MempoolTransaction{
Transaction: tx,
Fee: txDesc.Fee,
AddedTime: txDesc.Added.Unix(),
AddedHeight: txDesc.Height,
FeePerKb: txDesc.Fee / int64(uTx.MsgTx().SerializeSize()),
StartingPriority: txDesc.StartingPriority,
}
resp.UnconfirmedTransactions = append(resp.UnconfirmedTransactions, mempoolTx)
}
return resp, nil
}
// GetRawAddressTransactions returns the raw transactions for the given address. Offers offset,
// limit, and from block options.
//
// **Requires AddressIndex**
func (s *GrpcServer) GetRawAddressTransactions(ctx context.Context, req *pb.GetRawAddressTransactionsRequest) (*pb.GetRawAddressTransactionsResponse, error) {
if s.addrIndex == nil {
return nil, status.Error(codes.Unavailable, "addrindex required")
}
if req.NbFetch > maxAddressQuerySize {
return nil, status.Errorf(codes.InvalidArgument, "nbfetch exceeds max of %d", maxAddressQuerySize)
}
// Attempt to decode the supplied address.
addr, err := bchutil.DecodeAddress(req.Address, s.chainParams)
if err != nil {
return nil, status.Error(codes.InvalidArgument, "invalid address")
}
startHeight := int32(0)
if len(req.GetHash()) == 0 {
startHeight = req.GetHeight()
} else {
h, err := chainhash.NewHash(req.GetHash())
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "invalid hash: %v", err)
}
// If error here we'll just use the genesis
startHeight, _ = s.chain.BlockHeightByHash(h)
}
confirmedTxs, err := s.fetchTransactionsByAddress(addr, startHeight, int(req.NbFetch), int(req.NbSkip))
if err != nil {
return nil, err
}
resp := &pb.GetRawAddressTransactionsResponse{}
for _, cTx := range confirmedTxs {
resp.ConfirmedTransactions = append(resp.ConfirmedTransactions, cTx.txBytes)
}
unconfirmedTxs := s.addrIndex.UnconfirmedTxnsForAddress(addr)
for _, uTx := range unconfirmedTxs {
var buf bytes.Buffer
if err := uTx.MsgTx().BchEncode(&buf, wire.ProtocolVersion, wire.BaseEncoding); err != nil {
return nil, status.Error(codes.Internal, "error serializing mempool transaction")
}
resp.UnconfirmedTransactions = append(resp.UnconfirmedTransactions, buf.Bytes())
}
return resp, nil
}
// GetAddressUnspentOutputs returns all the unspent transaction outputs
// for the given address.
//
// **Requires AddressIndex**
func (s *GrpcServer) GetAddressUnspentOutputs(ctx context.Context, req *pb.GetAddressUnspentOutputsRequest) (*pb.GetAddressUnspentOutputsResponse, error) {
if s.addrIndex == nil {
return nil, status.Error(codes.Unavailable, "addrindex required")
}
if req.IncludeTokenMetadata && s.slpIndex == nil {
return nil, status.Error(codes.Unavailable, "slpindex required")
}
// Attempt to decode the supplied address.
addr, err := bchutil.DecodeAddress(req.Address, s.chainParams)
if err != nil {
return nil, status.Error(codes.InvalidArgument, "invalid address")
}
// use cash address format
addr, err = bchutil.ConvertSlpToCashAddress(addr, s.chainParams)
if err != nil {
return nil, status.Error(codes.Internal, "couldn't convert address to cash address format")
}
tokenMetadataSet := make(map[chainhash.Hash]struct{})
checkTxOutputs := func(tx *wire.MsgTx) ([]*pb.UnspentOutput, error) {
txHash := tx.TxHash()
var (
utxoView *blockchain.UtxoViewpoint
utxos []*pb.UnspentOutput
)
if req.IncludeMempool {
utxoView, err = s.txMemPool.FetchUtxoView(bchutil.NewTx(tx))
if err != nil {
return nil, err
}
} else {
utxoView, err = s.chain.FetchUtxoView(bchutil.NewTx(tx))
if err != nil {
return nil, err
}
}
entries := utxoView.Entries()
for i, out := range tx.TxOut {
op := wire.NewOutPoint(&txHash, uint32(i))
entry := entries[*op]
if entry == nil || entry.IsSpent() {
continue
}
pkScript := make([]byte, len(out.PkScript))
copy(pkScript, out.PkScript)
_, addrs, _, err := txscript.ExtractPkScriptAddrs(pkScript, s.chainParams)