diff --git a/go.mod b/go.mod index 2e3333acc1..9fd72e5891 100644 --- a/go.mod +++ b/go.mod @@ -62,4 +62,4 @@ retract ( v0.13.0-beta ) -go 1.17 +go 1.18 diff --git a/rpcclientv2/blochchaincmd.go b/rpcclientv2/blochchaincmd.go new file mode 100644 index 0000000000..49216c879a --- /dev/null +++ b/rpcclientv2/blochchaincmd.go @@ -0,0 +1,47 @@ +package rpcclientv2 + +import ( + "encoding/json" +) + +type GetDifficultyRpcCmd struct{} + +func (u GetDifficultyRpcCmd) Name() string { + return "getdifficulty" +} + +func (u GetDifficultyRpcCmd) Marshal() (json.RawMessage, error) { + return json.Marshal(u) +} + +type FutureGetDifficulty chan *Response + +type GetDifficultyResult float64 + +func (r FutureGetDifficulty) Receive() (GetDifficultyResult, error) { + res, err := ReceiveFuture(r) + if err != nil { + return 0, err + } + + // Unmarshal the result as a float64. + var difficulty float64 + err = json.Unmarshal(res, &difficulty) + if err != nil { + return 0, err + } + return GetDifficultyResult(difficulty), nil +} + +type GetDifficultyRpcCall struct { +} + +func (u *GetDifficultyRpcCall) MapReq(arg string) GetDifficultyRpcCmd { + return GetDifficultyRpcCmd{} +} + +func (u *GetDifficultyRpcCall) MapResp(resp chan *Response) MessageFuture[GetDifficultyResult] { + f := FutureGetDifficulty(resp) + + return &f +} diff --git a/rpcclientv2/request.go b/rpcclientv2/request.go new file mode 100644 index 0000000000..97ac14a9a2 --- /dev/null +++ b/rpcclientv2/request.go @@ -0,0 +1,59 @@ +package rpcclientv2 + +import ( + "encoding/json" +) + +type Response struct { + Resp json.RawMessage + Err error +} + +type Command interface { + Name() string + Marshal() (json.RawMessage, error) +} + +type Client interface { + SendCmd(cmd Command) chan *Response +} + +type MessageFuture[M any] interface { + Receive() (M, error) +} + +func ReceiveFuture(f chan *Response) (json.RawMessage, error) { + // Wait for a response on the returned channel. + r := <-f + return r.Resp, r.Err +} + +type RpcCall[Args any, Cmd Command, Resp any] interface { + MapReq(arg Args) Cmd + + MapResp(resp chan *Response) MessageFuture[Resp] +} + +func AsyncRequest[Args any, Cmd Command, Resp any]( + client Client, cmdReq RpcCall[Args, Cmd, Resp], args Args) MessageFuture[Resp] { + + jsonCmd := cmdReq.MapReq(args) + + resp := client.SendCmd(jsonCmd) + + return cmdReq.MapResp(resp) +} + +type FakeClient struct { +} + +func (m FakeClient) SendCmd(cmd Command) chan *Response { + responseChan := make(chan *Response, 1) + + result := Response{ + Resp: []byte("561651.5"), + Err: nil, + } + responseChan <- &result + return responseChan +}