forked from bitbegin/eth-wallet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rlp.red
41 lines (38 loc) · 930 Bytes
/
rlp.red
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
Red [
Title: "Recursive Length Prefix Encoding in Red"
File: %rlp.red
Author: "Qingtian Xie"
Notes: "RLP Encoding based on: https://github.com/ethereum/wiki/wiki/%5BEnglish%5D-RLP"
]
rlp: context [
encode-length: function [
len [integer!]
offset [integer!]
return: [binary!]
][
either len < 56 [
trim/head to-binary len + offset
][
len-bin: trim/head to-binary len
first-byte: trim/head to-binary offset + 55 + length? len-bin
rejoin [first-byte len-bin]
]
]
encode: function [data [any-type!] return: [binary!]][
either block? data [
buffer: make binary! 500
foreach v data [
append buffer encode v
]
rejoin [encode-length length? buffer 192 buffer]
][
buffer: to binary! data
if number? data [buffer: trim/head buffer]
either all [1 = length? buffer buffer/1 < 128][
buffer
][
rejoin [encode-length length? buffer 128 buffer]
]
]
]
]