forked from gitchain/gitchain
/
rpc_block.go
92 lines (80 loc) · 2.02 KB
/
rpc_block.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
package api
import (
"encoding/hex"
"net/http"
"github.com/gitchain/gitchain/server/context"
"github.com/inconshreveable/log15"
)
type BlockService struct {
srv *context.T
log log15.Logger
}
type GetLastBlockArgs struct {
}
type GetLastBlockReply struct {
Hash string
}
func (service *BlockService) GetLastBlock(r *http.Request, args *GetLastBlockArgs, reply *GetLastBlockReply) error {
block, err := service.srv.DB.GetLastBlock()
if err != nil {
return err
}
reply.Hash = hex.EncodeToString(block.Hash())
return nil
}
type GetBlockArgs struct {
Hash string
}
type GetBlockReply struct {
NextBlockHash string
PreviousBlockHash string
MerkleRootHash string
Timestamp int64
Bits uint32
Nonce uint32
NumTransactions int
}
func (service *BlockService) GetBlock(r *http.Request, args *GetBlockArgs, reply *GetBlockReply) error {
hash, err := hex.DecodeString(args.Hash)
if err != nil {
return err
}
block, err := service.srv.DB.GetBlock(hash)
if err != nil {
return err
}
nextblock, err := service.srv.DB.GetNextBlock(hash)
if err != nil {
return err
}
if nextblock != nil {
reply.NextBlockHash = hex.EncodeToString(nextblock.Hash())
}
reply.PreviousBlockHash = hex.EncodeToString(block.PreviousBlockHash)
reply.MerkleRootHash = hex.EncodeToString(block.MerkleRootHash)
reply.Timestamp = block.Timestamp
reply.Bits = block.Bits
reply.Nonce = block.Nonce
reply.NumTransactions = len(block.Transactions)
return nil
}
type BlockTransactionsArgs struct {
Hash string
}
type BlockTransactionsReply struct {
Transactions []string
}
func (service *BlockService) BlockTransactions(r *http.Request, args *BlockTransactionsArgs, reply *BlockTransactionsReply) error {
hash, err := hex.DecodeString(args.Hash)
if err != nil {
return err
}
block, err := service.srv.DB.GetBlock(hash)
if err != nil {
return err
}
for i := range block.Transactions {
reply.Transactions = append(reply.Transactions, hex.EncodeToString(block.Transactions[i].Hash()))
}
return nil
}