code wiki / (root) / nx_peerwire_test.nx

nx_peerwire_test.nx source

↩ module page · 56 lines · 2165 B

1// nx_peerwire_test.nx -- KAT for the peer wire protocol (BEP-3). 2// Native sovereign lane; exit 0 = pass, N = assertion N failed. 3 4import "nx_str.nx" 5import "nx_peerwire.nx" 6 7func main() -> i64 { 8 let ih: *u8 = sys_mmap(20) 9 let pid: *u8 = sys_mmap(20) 10 var i: i64 = 0 11 while i < 20 { ih[i] = 0x11; pid[i] = 0x22; i = i + 1 } 12 13 // handshake build (68 bytes) 14 let hs: *u8 = sys_mmap(128) 15 if nx_pw_build_handshake(ih, pid, hs) != 68 { return 1 } 16 if (hs[0] as i64) != 19 { return 2 } 17 if (hs[1] as i64) != 0x42 { return 3 } // 'B' 18 if (hs[28] as i64) != 0x11 { return 4 } // info_hash start 19 if (hs[48] as i64) != 0x22 { return 5 } // peer_id start 20 // parse back 21 let oih: *u8 = sys_mmap(20) 22 let opid: *u8 = sys_mmap(20) 23 if nx_pw_parse_handshake(hs, 68, oih, opid) != 1 { return 6 } 24 if (oih[0] as i64) != 0x11 { return 7 } 25 if (opid[19] as i64) != 0x22 { return 8 } 26 // a corrupt handshake (wrong pstrlen) is rejected 27 hs[0] = 18 28 if nx_pw_parse_handshake(hs, 68, oih, opid) != 0 { return 9 } 29 30 // have(5): len=5, id=4, payload index=5 31 let m: *u8 = sys_mmap(64) 32 nx_pw_build_have(5, m) 33 if nx_pw_msg_len(m) != 5 { return 10 } 34 if nx_pw_msg_id(m) != NX_PW_HAVE { return 11 } 35 if _pw_get_u32(m, 5) != 5 { return 12 } 36 37 // request(index=1, begin=16384, length=16384): len=13, id=6, 3 payloads 38 let r: *u8 = sys_mmap(64) 39 nx_pw_build_request(1, 16384, 16384, r) 40 if nx_pw_msg_len(r) != 13 { return 13 } 41 if nx_pw_msg_id(r) != NX_PW_REQUEST { return 14 } 42 if _pw_get_u32(r, 5) != 1 { return 15 } 43 if _pw_get_u32(r, 9) != 16384 { return 16 } 44 if _pw_get_u32(r, 13) != 16384 { return 17 } 45 46 // bitfield 0xA0 = 1010 0000 -> has pieces 0 and 2, not 1 or 3 47 let bf: *u8 = sys_mmap(1) 48 bf[0] = 0xA0 49 if nx_pw_bitfield_has(bf, 1, 0) != 1 { return 18 } 50 if nx_pw_bitfield_has(bf, 1, 1) != 0 { return 19 } 51 if nx_pw_bitfield_has(bf, 1, 2) != 1 { return 20 } 52 if nx_pw_bitfield_has(bf, 1, 3) != 0 { return 21 } 53 if nx_pw_bitfield_has(bf, 1, 99) != 0 { return 22 } // out of range 54 55 return 0 56}