Skip to content

Commit c14f24d

Browse files
refactor code and clean up (#1633)
1 parent ef6c9dd commit c14f24d

7 files changed

Lines changed: 105 additions & 23 deletions

File tree

api/accounts/accounts.go

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -401,15 +401,10 @@ func (a *Accounts) handleBatchCallData(batchCallData *api.BatchCallData) (txCtx
401401
}
402402

403403
if len(batchCallData.BlockRef) > 0 {
404-
blockRef, err := hexutil.Decode(batchCallData.BlockRef)
404+
blkRef, err := restutil.ParseBlockRef(batchCallData.BlockRef)
405405
if err != nil {
406-
return nil, 0, nil, errors.WithMessage(err, "blockRef")
406+
return nil, 0, nil, err
407407
}
408-
if len(blockRef) != 8 {
409-
return nil, 0, nil, errors.New("blockRef: invalid length")
410-
}
411-
var blkRef tx.BlockRef
412-
copy(blkRef[:], blockRef[:])
413408
txCtx.BlockRef = blkRef
414409
}
415410

api/accounts/accounts_test.go

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -454,13 +454,21 @@ func batchCall(t *testing.T) {
454454
require.NoError(t, err)
455455
assert.Equal(t, http.StatusBadRequest, statusCode, "invalid data")
456456

457-
// Request body has an invalid blockRef
457+
// Request body has a blockRef of invalid length
458458
badBlockRef := &api.BatchCallData{
459459
BlockRef: "0x00",
460460
}
461461
_, statusCode, err = tclient.RawHTTPClient().RawHTTPPost("/accounts/*", badBlockRef)
462462
require.NoError(t, err)
463-
assert.Equal(t, http.StatusInternalServerError, statusCode, "invalid blockRef")
463+
assert.Equal(t, http.StatusBadRequest, statusCode, "invalid length blockRef")
464+
465+
// Request body has a malformed (non-hex) blockRef
466+
malformedBlockRef := &api.BatchCallData{
467+
BlockRef: "not-hex",
468+
}
469+
_, statusCode, err = tclient.RawHTTPClient().RawHTTPPost("/accounts/*", malformedBlockRef)
470+
require.NoError(t, err)
471+
assert.Equal(t, http.StatusBadRequest, statusCode, "malformed blockRef")
464472

465473
// Request body has an invalid malformed revision
466474
_, statusCode, err = tclient.RawHTTPClient().RawHTTPPost(fmt.Sprintf("/accounts/*?revision=%s", "0xZZZ"), badBody)

api/debug/debug.go

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -439,6 +439,9 @@ func (d *Debug) parseTarget(target string) (block *block.Block, txID thor.Bytes3
439439
}
440440
block, err = d.repo.GetBlock(blockID)
441441
if err != nil {
442+
if d.repo.IsNotFound(err) {
443+
return nil, thor.Bytes32{}, 0, restutil.BadRequest(errors.WithMessage(err, "target[0]"))
444+
}
442445
return nil, thor.Bytes32{}, 0, err
443446
}
444447
if len(parts[1]) == 64 || len(parts[1]) == 66 {
@@ -513,15 +516,10 @@ func (d *Debug) handleTraceCallOption(opt *api.TraceCallOption) (*xenv.Transacti
513516
}
514517

515518
if len(opt.BlockRef) > 0 {
516-
blockRef, err := hexutil.Decode(opt.BlockRef)
519+
blkRef, err := restutil.ParseBlockRef(opt.BlockRef)
517520
if err != nil {
518-
return nil, 0, nil, errors.WithMessage(err, "blockRef")
519-
}
520-
if len(blockRef) != 8 {
521-
return nil, 0, nil, errors.New("blockRef: invalid length")
521+
return nil, 0, nil, err
522522
}
523-
var blkRef tx.BlockRef
524-
copy(blkRef[:], blockRef[:])
525523
txCtx.BlockRef = blkRef
526524
}
527525

api/debug/debug_test.go

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -88,9 +88,10 @@ func TestDebug(t *testing.T) {
8888

8989
// /storage/range endpoint
9090
for name, tt := range map[string]func(*testing.T){
91-
"testStorageRangeWithError": testStorageRangeWithError,
92-
"testStorageRange": testStorageRange,
93-
"testStorageRangeDefaultOption": testStorageRangeDefaultOption,
91+
"testStorageRangeWithError": testStorageRangeWithError,
92+
"testStorageRangeWithNonExistingBlockID": testStorageRangeWithNonExistingBlockID,
93+
"testStorageRange": testStorageRange,
94+
"testStorageRangeDefaultOption": testStorageRangeDefaultOption,
9495
} {
9596
t.Run(name, tt)
9697
}
@@ -181,7 +182,7 @@ func testTraceClauseWithNonExistingBlockID(t *testing.T) {
181182
Name: "structLogger",
182183
Target: fmt.Sprintf("%s/x/x", datagen.RandomHash()),
183184
}
184-
httpPostAndCheckResponseStatus(t, "/debug/tracers", traceClauseOption, 500)
185+
httpPostAndCheckResponseStatus(t, "/debug/tracers", traceClauseOption, 400)
185186
}
186187

187188
func testTraceClauseWithBadTxID(t *testing.T) {
@@ -465,7 +466,7 @@ func testHandleTraceCallWithBadBlockRef(t *testing.T) {
465466
BlockRef: "jh000000000000000",
466467
}
467468

468-
res := httpPostAndCheckResponseStatus(t, "/debug/tracers/call", traceCallOption, 500)
469+
res := httpPostAndCheckResponseStatus(t, "/debug/tracers/call", traceCallOption, 400)
469470

470471
assert.Equal(t, "blockRef: hex string without 0x prefix", strings.TrimSpace(res))
471472
}
@@ -485,7 +486,7 @@ func testHandleTraceCallWithInvalidLengthBlockRef(t *testing.T) {
485486
BlockRef: "0x00",
486487
}
487488

488-
res := httpPostAndCheckResponseStatus(t, "/debug/tracers/call", traceCallOption, 500)
489+
res := httpPostAndCheckResponseStatus(t, "/debug/tracers/call", traceCallOption, 400)
489490

490491
assert.Equal(t, "blockRef: invalid length", strings.TrimSpace(res))
491492
}
@@ -503,6 +504,15 @@ func testStorageRangeWithError(t *testing.T) {
503504
httpPostAndCheckResponseStatus(t, "/debug/storage-range", badMaxResult, 400)
504505
}
505506

507+
func testStorageRangeWithNonExistingBlockID(t *testing.T) {
508+
opt := &api.StorageRangeOption{
509+
Address: datagen.RandAddress(),
510+
Target: fmt.Sprintf("%s/0/0", datagen.RandomHash()),
511+
}
512+
res := httpPostAndCheckResponseStatus(t, "/debug/storage-range", opt, 400)
513+
assert.Contains(t, res, "target[0]")
514+
}
515+
506516
func testStorageRange(t *testing.T) {
507517
opt := api.StorageRangeOption{
508518
Address: datagen.RandAddress(),

api/restutil/http.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,12 @@ import (
1010
"io"
1111
"net/http"
1212

13+
"github.com/ethereum/go-ethereum/common/hexutil"
1314
"github.com/pkg/errors"
1415

1516
"github.com/vechain/thor/v2/log"
1617
"github.com/vechain/thor/v2/thor"
18+
"github.com/vechain/thor/v2/tx"
1719
)
1820

1921
var logger = log.WithContext("pkg", "http-utils")
@@ -114,6 +116,20 @@ func ParseJSON(r io.Reader, v any) error {
114116
return decoder.Decode(v)
115117
}
116118

119+
// ParseBlockRef parses a hex-encoded, 8-byte block reference from a request.
120+
func ParseBlockRef(blockRef string) (tx.BlockRef, error) {
121+
var blkRef tx.BlockRef
122+
decoded, err := hexutil.Decode(blockRef)
123+
if err != nil {
124+
return blkRef, BadRequest(errors.WithMessage(err, "blockRef"))
125+
}
126+
if len(decoded) != len(blkRef) {
127+
return blkRef, BadRequest(errors.New("blockRef: invalid length"))
128+
}
129+
copy(blkRef[:], decoded)
130+
return blkRef, nil
131+
}
132+
117133
// WriteJSON response an object in JSON encoding.
118134
func WriteJSON(w http.ResponseWriter, obj any) error {
119135
w.Header().Set("Content-Type", JSONContentType)

api/restutil/http_test.go

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import (
1717
"github.com/stretchr/testify/assert"
1818

1919
"github.com/vechain/thor/v2/api/restutil"
20+
"github.com/vechain/thor/v2/tx"
2021
)
2122

2223
func TestWrapHandlerFunc(t *testing.T) {
@@ -83,6 +84,52 @@ func TestWrapHandlerFuncWithNilCauseError(t *testing.T) {
8384
assert.Equal(t, "", response.Body.String())
8485
}
8586

87+
func TestParseBlockRef(t *testing.T) {
88+
tests := []struct {
89+
name string
90+
input string
91+
wantErr string
92+
wantRef tx.BlockRef
93+
wantBadR bool
94+
}{
95+
{
96+
name: "valid",
97+
input: "0x0102030405060708",
98+
wantRef: tx.BlockRef{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08},
99+
},
100+
{
101+
name: "malformed hex",
102+
input: "not-hex",
103+
wantErr: "blockRef: hex string without 0x prefix",
104+
wantBadR: true,
105+
},
106+
{
107+
name: "invalid length",
108+
input: "0x00",
109+
wantErr: "blockRef: invalid length",
110+
wantBadR: true,
111+
},
112+
}
113+
114+
for _, tt := range tests {
115+
t.Run(tt.name, func(t *testing.T) {
116+
ref, err := restutil.ParseBlockRef(tt.input)
117+
if tt.wantErr == "" {
118+
assert.NoError(t, err)
119+
assert.Equal(t, tt.wantRef, ref)
120+
return
121+
}
122+
assert.EqualError(t, err, tt.wantErr)
123+
// Malformed input must be classified as a client (400) error.
124+
handler := restutil.WrapHandlerFunc(func(_ http.ResponseWriter, _ *http.Request) error {
125+
return err
126+
})
127+
response := callWrappedFunc(&handler)
128+
assert.Equal(t, http.StatusBadRequest, response.Code)
129+
})
130+
}
131+
}
132+
86133
func callWrappedFunc(wrapped *http.HandlerFunc) *httptest.ResponseRecorder {
87134
req := httptest.NewRequest("GET", "http://example.com", nil)
88135

p2p/discv5/net.go

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -422,7 +422,15 @@ loop:
422422
case pkt := <-net.read:
423423
//fmt.Println("read", pkt.ev)
424424
log.Trace("<-net.read")
425-
n := net.internNode(&pkt)
425+
n := net.nodes[pkt.remoteID]
426+
if n == nil {
427+
if pkt.ev != pingPacket {
428+
log.Trace("dropping non-ping from unknown sender",
429+
"ev", pkt.ev, "id", pkt.remoteID[:8], "addr", pkt.remoteAddr)
430+
continue
431+
}
432+
n = net.internNode(&pkt)
433+
}
426434
prestate := n.state
427435
status := "ok"
428436
if err := net.handle(n, pkt.ev, &pkt); err != nil {

0 commit comments

Comments
 (0)