-
Notifications
You must be signed in to change notification settings - Fork 32
/
ProxyRPC.go
316 lines (267 loc) · 9.33 KB
/
ProxyRPC.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
package main
import (
"crypto/subtle"
"encoding/json"
"io/ioutil"
"net/http"
"strings"
"time"
"merkle-tree-and-bitcoin/hash"
"github.com/golang/glog"
)
// RPCResultCreateAuxBlock RPC方法createauxblock的返回结果
type RPCResultCreateAuxBlock struct {
Hash string `json:"hash"`
ChainID uint32 `json:"chainid"`
PrevBlockHash string `json:"previousblockhash"`
CoinbaseValue uint64 `json:"coinbasevalue"`
Bits string `json:"bits"`
Height uint32 `json:"height"`
Target string `json:"_target"`
MerkleSize uint32 `json:"merkle_size"`
MerkleNonce uint32 `json:"merkle_nonce"`
}
// write 输出JSON-RPC格式的信息
func write(w http.ResponseWriter, response interface{}) {
responseJSON, _ := json.Marshal(response)
w.Write(responseJSON)
}
// writeError 输出JSON-RPC格式的错误信息
func writeError(w http.ResponseWriter, id interface{}, errNo int, errMsg string) {
err := RPCError{errNo, errMsg}
response := RPCResponse{id, nil, err}
write(w, response)
}
// ProxyRPCHandle 代理RPC处理器
type ProxyRPCHandle struct {
config ProxyRPCServer
auxJobMaker *AuxJobMaker
dbhandle DBConnection
}
// NewProxyRPCHandle 创建代理RPC处理器
func NewProxyRPCHandle(config ProxyRPCServer, auxJobMaker *AuxJobMaker) (handle *ProxyRPCHandle) {
handle = new(ProxyRPCHandle)
handle.config = config
handle.auxJobMaker = auxJobMaker
handle.dbhandle.InitDB(config.PoolDb)
return
}
// basicAuth 执行Basic认证
func (handle *ProxyRPCHandle) basicAuth(r *http.Request) bool {
apiUser := []byte(handle.config.User)
apiPasswd := []byte(handle.config.Passwd)
user, passwd, ok := r.BasicAuth()
// 检查用户名密码是否正确
if ok && subtle.ConstantTimeCompare(apiUser, []byte(user)) == 1 && subtle.ConstantTimeCompare(apiPasswd, []byte(passwd)) == 1 {
return true
}
return false
}
func (handle *ProxyRPCHandle) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if !handle.basicAuth(r) {
// 认证失败,提示 401 Unauthorized
// Restricted 可以改成其他的值
w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
// 401 状态码
w.WriteHeader(http.StatusUnauthorized)
// 401 页面
w.Write([]byte(`<h1>401 - Unauthorized</h1>`))
return
}
if r.Method != "POST" {
w.Write([]byte("JSONRPC server handles only POST requests"))
return
}
requestJSON, err := ioutil.ReadAll(r.Body)
if err != nil {
writeError(w, nil, 400, err.Error())
return
}
var request RPCRequest
err = json.Unmarshal(requestJSON, &request)
if err != nil {
writeError(w, nil, 400, err.Error())
return
}
response := RPCResponse{request.ID, nil, nil}
switch request.Method {
case "createauxblock":
handle.createAuxBlock(&response)
case "submitauxblock":
handle.submitAuxBlock(request.Params, &response)
case "getauxblock":
if len(request.Params) > 0 {
handle.submitAuxBlock(request.Params, &response)
} else {
handle.createAuxBlock(&response)
}
default:
// 将未知方法转发给第一个chain的server
responseJSON, err := RPCCall(handle.auxJobMaker.chains[0].RPCServer, request.Method, request.Params)
if err != nil {
writeError(w, nil, 400, err.Error())
return
}
response, err = ParseRPCResponse(responseJSON)
if err != nil {
writeError(w, nil, 400, err.Error())
return
}
// 若调用的是help方法,则在结果后面追加对 createauxblock 和 submitauxblock 的描述
if request.Method == "help" && len(request.Params) == 0 {
helpStr, ok := response.Result.(string)
if ok {
helpStr += "\n\n== Merged Mining Proxy ==\n" +
"createauxblock <address>\n" +
"submitauxblock <hash> <auxpow>\n" +
"getauxblock (hash auxpow)"
response.Result = helpStr
}
}
}
write(w, response)
}
func (handle *ProxyRPCHandle) createAuxBlock(response *RPCResponse) {
job, err := handle.auxJobMaker.GetAuxJob()
if err != nil {
response.Error = RPCError{500, err.Error()}
return
}
var result RPCResultCreateAuxBlock
result.Bits = job.MinBits
result.ChainID = 1
result.CoinbaseValue = job.CoinbaseValue
result.Hash = job.MerkleRoot.HexReverse()
result.Height = job.Height
result.PrevBlockHash = job.PrevBlockHash.Hex()
result.Target = job.MaxTarget.HexReverse()
result.MerkleSize = job.MerkleSize
result.MerkleNonce = job.MerkleNonce
glog.Info("[CreateAuxBlock] height:", result.Height,
", bits:", result.Bits,
", target:", job.MaxTarget.Hex(),
", coinbaseValue:", result.CoinbaseValue,
", hash:", job.MerkleRoot.Hex(),
", prevHash:", result.PrevBlockHash,
", merkleSize: ", job.MerkleSize,
", merkleNonce: ", job.MerkleNonce)
response.Result = result
return
}
func (handle *ProxyRPCHandle) submitAuxBlock(params []interface{}, response *RPCResponse) {
if len(params) < 2 {
response.Error = RPCError{400, "The number of params should be 2"}
return
}
hashHex, ok := params[0].(string)
if !ok {
response.Error = RPCError{400, "The param 1 should be a string"}
return
}
auxPowHex, ok := params[1].(string)
if !ok {
response.Error = RPCError{400, "The param 2 should be a string"}
return
}
auxPowData, err := ParseAuxPowData(auxPowHex, handle.config.MainChain)
if err != nil {
response.Error = RPCError{400, err.Error()}
return
}
hashtmp, err := hash.MakeByte32FromHex(hashHex)
if err != nil {
response.Error = RPCError{400, err.Error()}
return
}
hashtmp = hashtmp.Reverse()
job, err := handle.auxJobMaker.FindAuxJob(hashtmp)
if err != nil {
response.Error = RPCError{400, err.Error()}
return
}
count := 0
for index, extAuxPow := range job.AuxPows {
if glog.V(3) {
glog.Info("[SubmitAuxBlock] <", handle.auxJobMaker.chains[index].Name, "> blockHash: ",
auxPowData.blockHash.Hex(), "; auxTarget: ", extAuxPow.Target.Hex())
}
// target reached
if auxPowData.blockHash.Hex() <= extAuxPow.Target.Hex() {
go func(index int, auxPowData AuxPowData, extAuxPow AuxPowInfo) {
chain := handle.auxJobMaker.chains[index]
auxPowData.ExpandingBlockchainBranch(extAuxPow.BlockchainBranch)
auxPowHex := auxPowData.ToHex()
// 切片是对原字符串的引用
// 对切片中字符串的修改会直接改变 chain.SubmitAuxBlock.Params 中的值
// 所以这里拷贝一份
params := DeepCopy(chain.SubmitAuxBlock.Params)
if paramsArr, ok := params.([]interface{}); ok { // JSON-RPC 1.0 param array
for i := range paramsArr {
if str, ok := paramsArr[i].(string); ok {
str = strings.Replace(str, "{hash-hex}", extAuxPow.Hash.HexReverse(), -1)
str = strings.Replace(str, "{aux-pow-hex}", auxPowHex, -1)
paramsArr[i] = str
}
}
} else if paramsMap, ok := params.(map[string]interface{}); ok { // JSON-RPC 2.0 param object
for k := range paramsMap {
if str, ok := paramsMap[k].(string); ok {
str = strings.Replace(str, "{hash-hex}", extAuxPow.Hash.HexReverse(), -1)
str = strings.Replace(str, "{aux-pow-hex}", auxPowHex, -1)
paramsMap[k] = str
}
}
}
responseJSON, _ := RPCCall(chain.RPCServer, chain.SubmitAuxBlock.Method, params)
var submitauxblockinfo SubmitAuxBlockInfo
response, err := ParseRPCResponse(responseJSON)
if response.Error != nil {
submitauxblockinfo.IsSubmitSuccess = false;
} else {
submitauxblockinfo.IsSubmitSuccess = true;
}
submitauxblockinfo.AuxBlockTableName = handle.auxJobMaker.chains[index].AuxTableName
if handle.config.MainChain == "LTC" {
submitauxblockinfo.ParentChainBllockHash = HexToString(ArrayReverse(DoubleSHA256(auxPowData.parentBlock)))
submitauxblockinfo.AuxChainBlockHash = extAuxPow.Hash.HexReverse()
} else {
submitauxblockinfo.ParentChainBllockHash = auxPowData.blockHash.Hex()
submitauxblockinfo.AuxChainBlockHash = extAuxPow.Hash.Hex()
}
submitauxblockinfo.ChainName = handle.auxJobMaker.chains[index].Name
submitauxblockinfo.AuxPow = auxPowHex
submitauxblockinfo.SubmitResponse = string(responseJSON)
submitauxblockinfo.CurrentTime = time.Now().Format("2006-01-02 15:04:05")
if ok = handle.dbhandle.InsertAuxBlock(submitauxblockinfo); !ok {
glog.Warning("Insert AuxBlock to db failed!")
}
glog.Info(
"[SubmitAuxBlock] <", handle.auxJobMaker.chains[index].Name, "> ",
", height: ", extAuxPow.Height,
", hash: ", submitauxblockinfo.AuxChainBlockHash,
", parentBlockHash: ", submitauxblockinfo.ParentChainBllockHash,
", target: ", extAuxPow.Target.Hex(),
", response: ", string(responseJSON),
", errmsg: ", err)
}(index, *auxPowData, extAuxPow)
count++
}
}
if count < 1 {
glog.Warning("[SubmitAuxBlock] high hash! blockHash: ", auxPowData.blockHash.Hex(), "; maxTarget: ", job.MaxTarget.Hex())
response.Error = RPCError{400, "high-hash"}
return
}
response.Result = true
return
}
func runHTTPServer(config ProxyRPCServer, auxJobMaker *AuxJobMaker) {
handle := NewProxyRPCHandle(config, auxJobMaker)
// HTTP监听
glog.Info("Listen HTTP ", config.ListenAddr)
err := http.ListenAndServe(config.ListenAddr, handle)
if err != nil {
glog.Fatal("HTTP Listen Failed: ", err)
return
}
}