77 "fmt"
88 "strings"
99
10- canonicaljson "github.com/gibson042/canonicaljson-go"
10+ jsonv2 "github.com/go-json-experiment/json"
11+ "github.com/go-json-experiment/json/jsontext"
1112)
1213
1314const (
@@ -63,22 +64,27 @@ func (r *Request[Params]) ServiceName() string {
6364// Digest returns a digest of the request. This is used for signature verification.
6465// The digest is a SHA256 hash of the canonical JSON string of the request excluding the auth field.
6566func (r * Request [Params ]) Digest () (string , error ) {
66- canonicalJSONBytes , err := canonicaljson .Marshal (Request [Params ]{
67+ JSONBytes , err := jsonv2 .Marshal (Request [Params ]{
6768 Version : r .Version ,
6869 ID : r .ID ,
6970 Method : r .Method ,
7071 Params : r .Params ,
7172 // Auth is intentionally excluded from the digest
72- })
73+ }, jsonv2 . Deterministic ( true ) )
7374 if err != nil {
7475 return "" , fmt .Errorf ("error marshaling JSON: %w" , err )
7576 }
7677
78+ canonicalJSONBytes := jsontext .Value (JSONBytes )
79+ err = canonicalJSONBytes .Canonicalize ()
80+ if err != nil {
81+ return "" , fmt .Errorf ("error canonicalizing JSON: %w" , err )
82+ }
83+
7784 hasher := sha256 .New ()
7885 hasher .Write (canonicalJSONBytes )
79- digestBytes := hasher .Sum (nil )
8086
81- return hex .EncodeToString (digestBytes ), nil
87+ return hex .EncodeToString (hasher . Sum ( nil ) ), nil
8288}
8389
8490type Response [Result any ] struct {
@@ -92,18 +98,23 @@ type Response[Result any] struct {
9298// Digest returns a digest of the response. This is used for signature verification.
9399// The digest is a SHA256 hash of the canonical JSON string of the response.
94100func (r * Response [Result ]) Digest () (string , error ) {
95- canonicalJSONBytes , err := canonicaljson .Marshal (r )
101+ JSONBytes , err := jsonv2 .Marshal (r , jsonv2 . Deterministic ( true ) )
96102 if err != nil {
97103 return "" , fmt .Errorf ("error marshaling JSON: %w" , err )
98104 }
99105
106+ canonicalJSONBytes := jsontext .Value (JSONBytes )
107+ err = canonicalJSONBytes .Canonicalize ()
108+ if err != nil {
109+ return "" , fmt .Errorf ("error canonicalizing JSON: %w" , err )
110+ }
111+
100112 hasher := sha256 .New ()
101113 if _ , err := hasher .Write (canonicalJSONBytes ); err != nil {
102114 return "" , fmt .Errorf ("error writing to hasher: %w" , err )
103115 }
104- digestBytes := hasher .Sum (nil )
105116
106- return hex .EncodeToString (digestBytes ), nil
117+ return hex .EncodeToString (hasher . Sum ( nil ) ), nil
107118}
108119
109120// WireError represents a structured error in a Response.
0 commit comments