/
misc.go
319 lines (280 loc) · 9.13 KB
/
misc.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
package rpc
import (
"bytes"
"encoding/base64"
"encoding/binary"
"encoding/hex"
"encoding/json"
"strconv"
"strings"
"github.com/copernet/copernicus/conf"
"github.com/copernet/copernicus/crypto"
"github.com/copernet/copernicus/logic/lwallet"
"github.com/copernet/copernicus/model"
"github.com/copernet/copernicus/model/chain"
"github.com/copernet/copernicus/net/server"
"github.com/copernet/copernicus/net/wire"
"github.com/copernet/copernicus/rpc/btcjson"
"github.com/copernet/copernicus/service"
"github.com/copernet/copernicus/util"
"github.com/copernet/copernicus/util/base58"
"github.com/copernet/copernicus/util/cashaddr"
)
// API version constants
const (
jsonrpcSemverString = "1.0.0"
jsonrpcSemverMajor = 1
jsonrpcSemverMinor = 1
jsonrpcSemverPatch = 0
)
var miscHandlers = map[string]commandHandler{
"getinfo": handleGetInfo,
"validateaddress": handleValidateAddress,
"createmultisig": handleCreatemultisig,
"verifymessage": handleVerifyMessage,
"signmessagewithprivkey": handleSignMessageWithPrivkey,
"setmocktime": handleSetMocktime,
"echo": handleEcho,
"help": handleHelp,
"stop": handleStop,
"version": handleVersion,
"uptime": handleUptime,
}
// handleUptime implements the uptime command.
func handleUptime(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) {
return util.GetTimeSec() - s.cfg.StartupTime, nil
}
func handleGetInfo(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) {
best := chain.GetInstance().Tip()
var height int32
if best != nil {
height = best.Height
}
request := &service.GetConnectionCountRequest{}
response, err := server.ProcessForRPC(request)
if err != nil {
return nil, btcjson.RPCError{
Code: btcjson.RPCInternalError,
Message: "Can not acquire connection count",
}
}
count, ok := response.(*service.GetConnectionCountResponse)
if !ok {
return nil, btcjson.RPCError{
Code: btcjson.RPCInternalError,
Message: "Server handle error",
}
}
ret := &btcjson.InfoChainResult{
Version: 1000000*conf.AppMajor + 10000*conf.AppMinor + 100*conf.AppPatch,
ProtocolVersion: int32(wire.ProtocolVersion),
Blocks: height,
TimeOffset: util.GetTimeOffsetSec(),
Connections: int32(count.Count),
Proxy: conf.Cfg.P2PNet.Proxy,
Difficulty: getDifficulty(chain.GetInstance().Tip()),
TestNet: model.ActiveNetParams.BitcoinNet == wire.TestNet3,
RelayFee: 0, // todo define DefaultMinRelayTxFee
}
return ret, nil
}
// handleValidateAddress implements the validateaddress command.
func handleValidateAddress(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) {
c := cmd.(*btcjson.ValidateAddressCmd)
result := &btcjson.ValidateAddressChainResult{}
scriptPubKey, rpcErr := getStandardScriptPubKey(c.Address, nil)
if rpcErr != nil {
// If the address is invalid, isvalid is the only property returned.
result.IsValid = false
return result, nil
}
result.IsValid = true
result.Address = c.Address
result.ScriptPubKey = hex.EncodeToString(scriptPubKey.GetData())
if lwallet.IsWalletEnable() {
addrType, keyHash, _ := decodeAddress(c.Address)
result.IsMine = lwallet.IsMine(scriptPubKey)
result.IsWatchOnly = false // TODO:NOT support watch-only yet
result.Account = lwallet.GetAccountName(keyHash)
result.IsScript = addrType == cashaddr.P2SH
if result.IsMine && !result.IsScript {
keyPair := lwallet.GetKeyPair(keyHash)
if keyPair != nil {
result.PubKey = keyPair.GetPublicKey().ToHexString()
result.IsCompressed = keyPair.GetPublicKey().Compressed
}
}
}
return result, nil
}
func handleCreatemultisig(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) {
return nil, nil
}
func handleVerifyMessage(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) {
/* c := cmd.(*btcjson.VerifyMessageCmd)
addr, err := bitaddr.AddressFromString(c.Address)
if err != nil {
return nil, btcjson.RPCError{
Code: btcjson.ErrRPCType,
Message: "Invalid address",
}
}
hash160 := addr.EncodeToPubKeyHash()
if hash160 == nil {
return nil, btcjson.RPCError{
Code: btcjson.ErrRPCType,
Message: "Address does not refer to key",
}
}
data := []byte(strMessageMagic + c.Message)
hash := chainhash.DoubleHashB(data)
originBytes, err := base64.StdEncoding.DecodeString(c.Signature)
if err != nil {
return nil, btcjson.RPCError{
Code: btcjson.RPCInvalidAddressOrKey,
Message: "Malformed base64 encoding",
}
}
var pk crypto.PublicKey
pk, wasCompressed, err := RecoverCompact(curveInstance, originBytes, hash) // todo realise
if err != nil {
return false, nil
}
pubKeyBytes := pk.ToBytes()
addr2, err := bitaddr.AddressFromPublicKey(pubKeyBytes)
if err != nil {
return nil, btcjson.RPCError{
Code: btcjson.RPCInvalidAddressOrKey,
Message: "Invalid Public Key encoding",
}
}
return bytes.Equal(addr2.EncodeToPubKeyHash(), hash160), nil*/ //todo open
return nil, nil
}
func handleSignMessageWithPrivkey(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) {
c := cmd.(*btcjson.SignMessageWithPrivkeyCmd)
bs, _, err := base58.CheckDecode(c.Privkey)
if err != nil {
return nil, btcjson.RPCError{
Code: btcjson.RPCInvalidAddressOrKey,
Message: "Invalid private key",
}
}
privKey := crypto.PrivateKeyFromBytes(bs)
buf := bytes.NewBuffer(make([]byte, 0, 4+len(c.Message)))
err = util.BinarySerializer.PutUint32(buf, binary.LittleEndian, uint32(chain.GetInstance().GetParams().BitcoinNet))
if err != nil {
return nil, btcjson.RPCError{
Code: btcjson.RPCInternalError,
Message: "serialize BitcoinNet error",
}
}
buf.Write([]byte(c.Message))
originBytes := util.DoubleSha256Bytes(buf.Bytes())
signature, err := privKey.Sign(originBytes)
if err != nil {
return nil, btcjson.RPCError{
Code: btcjson.RPCInvalidAddressOrKey,
Message: "Sign failed",
}
}
return base64.StdEncoding.EncodeToString(signature.Serialize()), nil
}
func handleSetMocktime(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) {
c := cmd.(*btcjson.SetMocktimeCmd)
if !model.ActiveNetParams.MineBlocksOnDemands {
return nil, btcjson.RPCError{
Code: btcjson.RPCForbiddenBySafeMode,
Message: "etmocktime for regression testing (-regtest mode) only",
}
}
// For now, don't change mocktime if we're in the middle of validation, as
// this could have an effect on mempool time-based eviction, as well as
// IsCurrentForFeeEstimation() and IsInitialBlockDownload().
// figure out the right way to synchronize around mocktime, and
// ensure all callsites of GetTimeSec() are accessing this safely.
util.SetMockTime(c.Timestamp)
return nil, nil
}
func handleEcho(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) {
const echoArgPrefix = "arg"
if _, ok := cmd.(*map[string]json.RawMessage); !ok {
return cmd, nil
}
// JSON format
params := cmd.(*map[string]json.RawMessage)
retLen := 0
args := make(map[int]interface{})
for argName, arg := range *params {
if !strings.HasPrefix(strings.ToLower(argName), echoArgPrefix) {
return nil, btcjson.RPCError{
Code: btcjson.ErrRPCInvalidParameter,
Message: "Unknown named parameter " + argName,
}
}
argIdx := argName[len(echoArgPrefix):]
if index, err := strconv.Atoi(argIdx); err == nil {
args[index] = arg
if index >= retLen {
retLen = index + 1
}
}
}
result := make([]interface{}, retLen)
for index, arg := range args {
result[index] = arg
}
return result, nil
}
// handleHelp implements the help command.
func handleHelp(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) {
c := cmd.(*btcjson.HelpCmd)
var command string
if c.Command != nil {
command = *c.Command
}
if command == "" {
usage, err := s.helpCacher.rpcUsage(false)
if err != nil {
context := "Failed to generate RPC usage"
return nil, internalRPCError(err.Error(), context)
}
return usage, nil
}
if _, ok := rpcHandlers[command]; !ok {
return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCInvalidParameter,
Message: "Unknown command: " + command,
}
}
help, err := s.helpCacher.rpcMethodHelp(command)
if err != nil {
context := "Failed to generate help"
return nil, internalRPCError(err.Error(), context)
}
return help, nil
}
// handleStop implements the stop command.
func handleStop(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) {
select {
case s.requestProcessShutdown <- struct{}{}:
default:
}
return "Copernicus server stopping", nil
}
func handleVersion(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) {
result := map[string]btcjson.VersionResult{
"btcdjsonrpcapi": {
VersionString: jsonrpcSemverString,
Major: jsonrpcSemverMajor,
Minor: jsonrpcSemverMinor,
Patch: jsonrpcSemverPatch,
},
}
return result, nil
}
func registerMiscRPCCommands() {
for name, handler := range miscHandlers {
appendCommand(name, handler)
}
}