├── .github └── workflows │ └── pr.yaml ├── LICENSE ├── README.md ├── arena.go ├── arena_test.go ├── encode.go ├── fuzz.go ├── fuzz_test.go ├── go.mod ├── go.sum ├── interface.go ├── keccak.go ├── parser.go ├── parser_test.go └── pool.go /.github/workflows/pr.yaml: -------------------------------------------------------------------------------- 1 | name: Unit tests 2 | on: [pull_request] 3 | jobs: 4 | build: 5 | runs-on: ubuntu-latest 6 | name: Go test 7 | steps: 8 | - uses: actions/checkout@v2 9 | - name: Setup go 10 | uses: actions/setup-go@v1 11 | with: 12 | go-version: '1.18' 13 | - name: Unit tests 14 | run: go test -v ./... -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # FastRlp 3 | 4 | FastRlp is a high performant encoding/decoding library for the RLP Ethereum format. This library is based on [fastjson](https://github.com/valyala/fastjson). 5 | 6 | ## Usage 7 | 8 | FastRlp does not uses reflect to avoid bottlenecks. It provides a single value primitive that can be encoded or decoded into any specific type. 9 | 10 | Encode: 11 | 12 | ``` 13 | a := &fastrlp.Arena{} 14 | 15 | // Encode a uint 16 | v := a.NewUint(300) 17 | buf := v.MarshalTo(nil) 18 | 19 | // Encode an array 20 | v = a.NewArray() 21 | v.Set(a.NewUint(300)) 22 | buf = v.MarshalTo(nil) 23 | ``` 24 | 25 | You can find more examples [here](https://github.com/umbracle/fastrlp/blob/master/arena_test.go#L53). 26 | 27 | Decode: 28 | 29 | ``` 30 | p := &fastrlp.Parser{} 31 | v, err := p.Parse([]byte{0x01}) 32 | if err != nil { 33 | panic(err) 34 | } 35 | 36 | num, err := v.GetUint64() 37 | if err != nil { 38 | panic(err) 39 | } 40 | fmt.Println(num) 41 | ``` 42 | 43 | ## Benchmark 44 | 45 | ``` 46 | $ go-rlp-test go test -v ./. -run=XX -bench=. 47 | goos: linux 48 | goarch: amd64 49 | pkg: github.com/ferranbt/go-rlp-test 50 | BenchmarkDecode100HeadersGeth-8 10000 196183 ns/op 32638 B/op 1002 allocs/op 51 | BenchmarkEncode100HeadersGeth-8 10000 179328 ns/op 88471 B/op 1003 allocs/op 52 | BenchmarkDecode100HeadersFastRlp-8 30000 57179 ns/op 16 B/op 0 allocs/op 53 | BenchmarkEncode100HeadersFastRlp-8 30000 43967 ns/op 23 B/op 0 allocs/op 54 | PASS 55 | ok github.com/ferranbt/go-rlp-test 7.890s 56 | ``` 57 | -------------------------------------------------------------------------------- /arena.go: -------------------------------------------------------------------------------- 1 | package fastrlp 2 | 3 | import ( 4 | "encoding/binary" 5 | "math/big" 6 | ) 7 | 8 | // Arena is a pool of RLP values. 9 | type Arena struct { 10 | c cache 11 | } 12 | 13 | // Reset resets the values allocated in the arena. 14 | func (a *Arena) Reset() { 15 | a.c.reset() 16 | } 17 | 18 | // NewString returns a new string value. 19 | func (a *Arena) NewString(s string) *Value { 20 | return a.NewBytes([]byte(s)) 21 | } 22 | 23 | // NewBigInt returns a new big.int value. 24 | func (a *Arena) NewBigInt(b *big.Int) *Value { 25 | if b == nil { 26 | return valueNull 27 | } 28 | return a.NewBytes(b.Bytes()) 29 | } 30 | 31 | // NewCopyBytes returns a bytes value that copies the input. 32 | func (a *Arena) NewCopyBytes(b []byte) *Value { 33 | v := a.c.getValue() 34 | v.t = TypeBytes 35 | v.b = append(v.b[:0], b...) 36 | v.l = uint64(len(b)) 37 | return v 38 | } 39 | 40 | // NewBytes returns a bytes value. 41 | func (a *Arena) NewBytes(b []byte) *Value { 42 | return a.NewCopyBytes(b) 43 | } 44 | 45 | // NewUint returns a new uint value. 46 | func (a *Arena) NewUint(i uint64) *Value { 47 | if i == 0 { 48 | return valueNull 49 | } 50 | 51 | intSize := intsize(i) 52 | binary.BigEndian.PutUint64(a.c.buf[:], i) 53 | 54 | v := a.c.getValue() 55 | v.t = TypeBytes 56 | v.b = append(v.b[:0], a.c.buf[8-intSize:]...) 57 | v.l = intSize 58 | return v 59 | } 60 | 61 | // NewArray returns a new array value. 62 | func (a *Arena) NewArray() *Value { 63 | v := a.c.getValue() 64 | v.t = TypeArray 65 | v.a = v.a[:0] 66 | v.l = 0 67 | return v 68 | } 69 | 70 | // NewBool returns a new bool value. 71 | func (a *Arena) NewBool(b bool) *Value { 72 | if b { 73 | return valueTrue 74 | } 75 | return valueFalse 76 | } 77 | 78 | // NewTrue returns a true value. 79 | func (a *Arena) NewTrue() *Value { 80 | return valueTrue 81 | } 82 | 83 | // NewFalse returns a false value. 84 | func (a *Arena) NewFalse() *Value { 85 | return valueFalse 86 | } 87 | 88 | // NewNullArray returns a null array value. 89 | func (a *Arena) NewNullArray() *Value { 90 | return valueArrayNull 91 | } 92 | 93 | // NewNull returns a new null value. 94 | func (a *Arena) NewNull() *Value { 95 | return valueNull 96 | } 97 | -------------------------------------------------------------------------------- /arena_test.go: -------------------------------------------------------------------------------- 1 | package fastrlp 2 | 3 | import ( 4 | "bytes" 5 | "encoding/hex" 6 | "fmt" 7 | "strings" 8 | "testing" 9 | "time" 10 | ) 11 | 12 | func TestArena(t *testing.T) { 13 | t.Run("serial", func(t *testing.T) { 14 | var a Arena 15 | for i := 0; i < 10; i++ { 16 | if err := testArena(&a); err != nil { 17 | t.Fatal(err) 18 | } 19 | a.Reset() 20 | } 21 | }) 22 | 23 | t.Run("concurrent", func(t *testing.T) { 24 | var ap ArenaPool 25 | workers := 4 26 | ch := make(chan error, workers) 27 | for i := 0; i < workers; i++ { 28 | go func() { 29 | a := ap.Get() 30 | defer ap.Put(a) 31 | var err error 32 | for i := 0; i < 10; i++ { 33 | if err = testArena(a); err != nil { 34 | break 35 | } 36 | } 37 | ch <- err 38 | }() 39 | } 40 | for i := 0; i < workers; i++ { 41 | select { 42 | case err := <-ch: 43 | if err != nil { 44 | t.Fatal(err) 45 | } 46 | case <-time.After(time.Second): 47 | t.Fatalf("timeout") 48 | } 49 | } 50 | }) 51 | } 52 | 53 | func testArena(a *Arena) error { 54 | var v *Value 55 | 56 | // empty string 57 | v = a.NewString("") 58 | if err := validate(v, "0x80"); err != nil { 59 | return err 60 | } 61 | 62 | // bytestring00 63 | v = a.NewBytes([]byte{0x0}) 64 | if err := validate(v, "0x00"); err != nil { 65 | return err 66 | } 67 | 68 | // bytestring01 69 | v = a.NewBytes([]byte{0x1}) 70 | if err := validate(v, "0x01"); err != nil { 71 | return err 72 | } 73 | 74 | // bytestring7F 75 | v = a.NewBytes([]byte{0x7F}) 76 | if err := validate(v, "0x7F"); err != nil { 77 | return err 78 | } 79 | 80 | // short string 81 | v = a.NewString("dog") 82 | if err := validate(v, "0x83646f67"); err != nil { 83 | return err 84 | } 85 | 86 | // short string2 87 | v = a.NewString("Lorem ipsum dolor sit amet, consectetur adipisicing eli") 88 | if err := validate(v, "0xb74c6f72656d20697073756d20646f6c6f722073697420616d65742c20636f6e7365637465747572206164697069736963696e6720656c69"); err != nil { 89 | return err 90 | } 91 | 92 | // long string 93 | v = a.NewString("Lorem ipsum dolor sit amet, consectetur adipisicing elit") 94 | if err := validate(v, "0xb8384c6f72656d20697073756d20646f6c6f722073697420616d65742c20636f6e7365637465747572206164697069736963696e6720656c6974"); err != nil { 95 | return err 96 | } 97 | 98 | // long string 2 99 | v = a.NewString("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur mauris magna, suscipit sed vehicula non, iaculis faucibus tortor. Proin suscipit ultricies malesuada. Duis tortor elit, dictum quis tristique eu, ultrices at risus. Morbi a est imperdiet mi ullamcorper aliquet suscipit nec lorem. Aenean quis leo mollis, vulputate elit varius, consequat enim. Nulla ultrices turpis justo, et posuere urna consectetur nec. Proin non convallis metus. Donec tempor ipsum in mauris congue sollicitudin. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Suspendisse convallis sem vel massa faucibus, eget lacinia lacus tempor. Nulla quis ultricies purus. Proin auctor rhoncus nibh condimentum mollis. Aliquam consequat enim at metus luctus, a eleifend purus egestas. Curabitur at nibh metus. Nam bibendum, neque at auctor tristique, lorem libero aliquet arcu, non interdum tellus lectus sit amet eros. Cras rhoncus, metus ac ornare cursus, dolor justo ultrices metus, at ullamcorper volutpat") 100 | if err := validate(v, "0xb904004c6f72656d20697073756d20646f6c6f722073697420616d65742c20636f6e73656374657475722061646970697363696e6720656c69742e20437572616269747572206d6175726973206d61676e612c20737573636970697420736564207665686963756c61206e6f6e2c20696163756c697320666175636962757320746f72746f722e2050726f696e20737573636970697420756c74726963696573206d616c6573756164612e204475697320746f72746f7220656c69742c2064696374756d2071756973207472697374697175652065752c20756c7472696365732061742072697375732e204d6f72626920612065737420696d70657264696574206d6920756c6c616d636f7270657220616c6971756574207375736369706974206e6563206c6f72656d2e2041656e65616e2071756973206c656f206d6f6c6c69732c2076756c70757461746520656c6974207661726975732c20636f6e73657175617420656e696d2e204e756c6c6120756c74726963657320747572706973206a7573746f2c20657420706f73756572652075726e6120636f6e7365637465747572206e65632e2050726f696e206e6f6e20636f6e76616c6c6973206d657475732e20446f6e65632074656d706f7220697073756d20696e206d617572697320636f6e67756520736f6c6c696369747564696e2e20566573746962756c756d20616e746520697073756d207072696d697320696e206661756369627573206f726369206c756374757320657420756c74726963657320706f737565726520637562696c69612043757261653b2053757370656e646973736520636f6e76616c6c69732073656d2076656c206d617373612066617563696275732c2065676574206c6163696e6961206c616375732074656d706f722e204e756c6c61207175697320756c747269636965732070757275732e2050726f696e20617563746f722072686f6e637573206e69626820636f6e64696d656e74756d206d6f6c6c69732e20416c697175616d20636f6e73657175617420656e696d206174206d65747573206c75637475732c206120656c656966656e6420707572757320656765737461732e20437572616269747572206174206e696268206d657475732e204e616d20626962656e64756d2c206e6571756520617420617563746f72207472697374697175652c206c6f72656d206c696265726f20616c697175657420617263752c206e6f6e20696e74657264756d2074656c6c7573206c65637475732073697420616d65742065726f732e20437261732072686f6e6375732c206d65747573206163206f726e617265206375727375732c20646f6c6f72206a7573746f20756c747269636573206d657475732c20617420756c6c616d636f7270657220766f6c7574706174"); err != nil { 101 | return err 102 | } 103 | 104 | // zero 105 | v = a.NewUint(0) 106 | if err := validate(v, "0x80"); err != nil { 107 | return err 108 | } 109 | 110 | // smallint 111 | v = a.NewUint(1) 112 | if err := validate(v, "0x01"); err != nil { 113 | return err 114 | } 115 | 116 | // smallint2 117 | v = a.NewUint(16) 118 | if err := validate(v, "0x10"); err != nil { 119 | return err 120 | } 121 | 122 | // smallint3 123 | v = a.NewUint(79) 124 | if err := validate(v, "0x4f"); err != nil { 125 | return err 126 | } 127 | 128 | // smallint4 129 | v = a.NewUint(127) 130 | if err := validate(v, "0x7f"); err != nil { 131 | return err 132 | } 133 | 134 | // medium int 135 | 136 | // mediumint1 137 | v = a.NewUint(128) 138 | if err := validate(v, "0x8180"); err != nil { 139 | return err 140 | } 141 | 142 | // mediumint2 143 | v = a.NewUint(1000) 144 | if err := validate(v, "0x8203e8"); err != nil { 145 | return err 146 | } 147 | 148 | // mediumint3 149 | v = a.NewUint(100000) 150 | if err := validate(v, "0x830186a0"); err != nil { 151 | return err 152 | } 153 | 154 | // emptylist 155 | v = a.NewArray() 156 | if err := validate(v, "0xc0"); err != nil { 157 | return err 158 | } 159 | 160 | // stringlist 161 | v = a.NewArray() 162 | v.Set(a.NewString("dog")) 163 | v.Set(a.NewString("god")) 164 | v.Set(a.NewString("cat")) 165 | if err := validate(v, "0xcc83646f6783676f6483636174"); err != nil { 166 | return err 167 | } 168 | 169 | // multilist 170 | v = a.NewArray() 171 | v.Set(a.NewString("zw")) 172 | vv := a.NewArray() 173 | vv.Set(a.NewUint(4)) 174 | v.Set(vv) 175 | v.Set(a.NewUint(1)) 176 | if err := validate(v, "0xc6827a77c10401"); err != nil { 177 | return err 178 | } 179 | 180 | // TODO, build the rest of the tests 181 | return nil 182 | } 183 | 184 | func validate(v *Value, expected string) error { 185 | if strings.HasPrefix(expected, "0x") { 186 | expected = expected[2:] 187 | } 188 | buf, err := hex.DecodeString(expected) 189 | if err != nil { 190 | return err 191 | } 192 | dst := v.MarshalTo(nil) 193 | if !bytes.Equal(dst, buf) { 194 | return fmt.Errorf("bad") 195 | } 196 | return nil 197 | } 198 | -------------------------------------------------------------------------------- /encode.go: -------------------------------------------------------------------------------- 1 | package fastrlp 2 | 3 | import ( 4 | "bytes" 5 | "encoding/binary" 6 | "fmt" 7 | "math/big" 8 | "sync" 9 | ) 10 | 11 | // bufPool to convert int to bytes 12 | var bufPool = sync.Pool{ 13 | New: func() interface{} { 14 | buf := make([]byte, 8) 15 | return &buf 16 | }, 17 | } 18 | 19 | type cache struct { 20 | buf [8]byte 21 | vs []Value 22 | size uint64 23 | indx uint64 24 | } 25 | 26 | func (c *cache) reset() { 27 | c.vs = c.vs[:0] 28 | c.size = 0 29 | c.indx = 0 30 | } 31 | 32 | func (c *cache) getValue() *Value { 33 | if cap(c.vs) > len(c.vs) { 34 | c.vs = c.vs[:len(c.vs)+1] 35 | } else { 36 | c.vs = append(c.vs, Value{}) 37 | } 38 | return &c.vs[len(c.vs)-1] 39 | } 40 | 41 | // Type represents an RLP type. 42 | type Type int 43 | 44 | const ( 45 | // TypeArray is an RLP array value. 46 | TypeArray Type = iota 47 | 48 | // TypeBytes is an RLP bytes value. 49 | TypeBytes 50 | 51 | // TypeNull is an RLP bytes null (0x80) 52 | TypeNull 53 | 54 | // TypeArrayNull is an RLP array null (0xC0) 55 | TypeArrayNull 56 | ) 57 | 58 | // String returns the string representation of the type. 59 | func (t Type) String() string { 60 | switch t { 61 | case TypeArray: 62 | return "array" 63 | case TypeBytes: 64 | return "bytes" 65 | case TypeNull: 66 | return "null" 67 | case TypeArrayNull: 68 | return "null-array" 69 | default: 70 | panic(fmt.Errorf("BUG: unknown Value type: %d", t)) 71 | } 72 | } 73 | 74 | // Value is an RLP value 75 | type Value struct { 76 | // t is the type of the value, either Bytes or Array 77 | t Type 78 | 79 | // a are the list of objects for the type array 80 | a []*Value 81 | 82 | // b is the bytes content of the bytes type 83 | b []byte 84 | 85 | // l is the length of the value 86 | l uint64 87 | 88 | // i is the starting index in the bytes input buffer 89 | i uint64 90 | } 91 | 92 | // GetString returns string value. 93 | func (v *Value) GetString() (string, error) { 94 | if v.t != TypeBytes { 95 | return "", errNoBytes() 96 | } 97 | return string(v.b), nil 98 | } 99 | 100 | // GetElems returns the elements of an array. 101 | func (v *Value) GetElems() ([]*Value, error) { 102 | if v.t != TypeArray { 103 | return nil, errNoArray() 104 | } 105 | return v.a, nil 106 | } 107 | 108 | // GetBigInt returns big.int value. 109 | func (v *Value) GetBigInt(b *big.Int) error { 110 | if v.t != TypeBytes { 111 | return errNoBytes() 112 | } 113 | b.SetBytes(v.b) 114 | return nil 115 | } 116 | 117 | // GetBool returns bool value. 118 | func (v *Value) GetBool() (bool, error) { 119 | if v.t != TypeBytes { 120 | return false, errNoBytes() 121 | } 122 | if bytes.Equal(v.b, valueTrue.b) { 123 | return true, nil 124 | } 125 | if bytes.Equal(v.b, valueFalse.b) { 126 | return false, nil 127 | } 128 | return false, fmt.Errorf("not a valid bool") 129 | } 130 | 131 | // Raw returns the raw bytes 132 | func (v *Value) Raw() []byte { 133 | return v.b 134 | } 135 | 136 | // Bytes returns the raw bytes. 137 | func (v *Value) Bytes() ([]byte, error) { 138 | if v.t != TypeBytes { 139 | return nil, errNoBytes() 140 | } 141 | return v.b, nil 142 | } 143 | 144 | // GetBytes returns bytes to dst. 145 | func (v *Value) GetBytes(dst []byte, bits ...int) ([]byte, error) { 146 | if v.t != TypeBytes { 147 | return nil, errNoBytes() 148 | } 149 | if len(bits) > 0 { 150 | if len(v.b) != bits[0] { 151 | return nil, fmt.Errorf("bad length, expected %d but found %d", bits[0], len(v.b)) 152 | } 153 | } 154 | dst = append(dst[:0], v.b...) 155 | return dst, nil 156 | } 157 | 158 | // GetAddr returns bytes of size 20. 159 | func (v *Value) GetAddr(buf []byte) error { 160 | _, err := v.GetBytes(buf, 20) 161 | return err 162 | } 163 | 164 | // GetHash returns bytes of size 32. 165 | func (v *Value) GetHash(buf []byte) error { 166 | _, err := v.GetBytes(buf, 32) 167 | return err 168 | } 169 | 170 | // GetByte returns a byte 171 | func (v *Value) GetByte() (byte, error) { 172 | if v.t != TypeBytes { 173 | return 0, errNoBytes() 174 | } 175 | if len(v.b) != 1 { 176 | return 0, fmt.Errorf("bad length, expected 1 but found %d", len(v.b)) 177 | } 178 | return byte(v.b[0]), nil 179 | } 180 | 181 | // GetUint64 returns uint64. 182 | func (v *Value) GetUint64() (uint64, error) { 183 | if v.t != TypeBytes { 184 | return 0, errNoBytes() 185 | } 186 | if len(v.b) > 8 { 187 | return 0, fmt.Errorf("bytes %d too long for uint64", len(v.b)) 188 | } 189 | 190 | buf := bufPool.Get().(*[]byte) 191 | num := readUint(v.b, *buf) 192 | bufPool.Put(buf) 193 | 194 | return num, nil 195 | } 196 | 197 | // Type returns the type of the value 198 | func (v *Value) Type() Type { 199 | return v.t 200 | } 201 | 202 | // Get returns the item at index i in the array 203 | func (v *Value) Get(i int) *Value { 204 | if i > len(v.a) { 205 | return nil 206 | } 207 | return v.a[i] 208 | } 209 | 210 | // Elems returns the number of elements if its an array 211 | func (v *Value) Elems() int { 212 | return len(v.a) 213 | } 214 | 215 | // Len returns the raw size of the value 216 | func (v *Value) Len() uint64 { 217 | if v.t == TypeArray { 218 | return v.l + intsize(v.l) 219 | } 220 | return v.l 221 | } 222 | 223 | func (v *Value) fullLen() uint64 { 224 | // null 225 | if v.t == TypeNull || v.t == TypeArrayNull { 226 | return 1 227 | } 228 | // bytes 229 | size := v.l 230 | if v.t == TypeBytes { 231 | if size == 1 && v.b[0] <= 0x7F { 232 | return 1 233 | } else if size < 56 { 234 | return 1 + size 235 | } else { 236 | return 1 + intsize(size) + size 237 | } 238 | } 239 | // array 240 | if size < 56 { 241 | return 1 + size 242 | } 243 | return 1 + intsize(size) + size 244 | } 245 | 246 | // Set sets a value in the array 247 | func (v *Value) Set(vv *Value) { 248 | if v == nil || v.t != TypeArray { 249 | return 250 | } 251 | v.l += vv.fullLen() 252 | v.a = append(v.a, vv) 253 | } 254 | 255 | func (v *Value) marshalLongSize(dst []byte) []byte { 256 | return v.marshalSize(dst, 0xC0, 0xF7) 257 | } 258 | 259 | func (v *Value) marshalShortSize(dst []byte) []byte { 260 | return v.marshalSize(dst, 0x80, 0xB7) 261 | } 262 | 263 | func (v *Value) marshalSize(dst []byte, short, long byte) []byte { 264 | if v.l < 56 { 265 | return append(dst, short+byte(v.l)) 266 | } 267 | 268 | intSize := intsize(v.l) 269 | 270 | buf := bufPool.Get().(*[]byte) 271 | binary.BigEndian.PutUint64((*buf)[:], uint64(v.l)) 272 | 273 | dst = append(dst, long+byte(intSize)) 274 | dst = append(dst, (*buf)[8-intSize:]...) 275 | 276 | bufPool.Put(buf) 277 | return dst 278 | } 279 | 280 | // MarshalTo appends marshaled v to dst and returns the result. 281 | func (v *Value) MarshalTo(dst []byte) []byte { 282 | switch v.t { 283 | case TypeBytes: 284 | if len(v.b) == 1 && v.b[0] <= 0x7F { 285 | // single element 286 | return append(dst, v.b...) 287 | } 288 | dst = v.marshalShortSize(dst) 289 | return append(dst, v.b...) 290 | case TypeArray: 291 | dst = v.marshalLongSize(dst) 292 | for _, vv := range v.a { 293 | dst = vv.MarshalTo(dst) 294 | } 295 | return dst 296 | case TypeNull: 297 | return append(dst, []byte{0x80}...) 298 | case TypeArrayNull: 299 | return append(dst, []byte{0xC0}...) 300 | default: 301 | panic(fmt.Errorf("BUG: unexpected Value type: %d", v.t)) 302 | } 303 | } 304 | 305 | var ( 306 | valueArrayNull = &Value{t: TypeArrayNull, l: 1} 307 | valueNull = &Value{t: TypeNull, l: 1} 308 | valueFalse = valueNull 309 | valueTrue = &Value{t: TypeBytes, b: []byte{0x1}, l: 1} 310 | ) 311 | 312 | func intsize(val uint64) uint64 { 313 | switch { 314 | case val < (1 << 8): 315 | return 1 316 | case val < (1 << 16): 317 | return 2 318 | case val < (1 << 24): 319 | return 3 320 | case val < (1 << 32): 321 | return 4 322 | case val < (1 << 40): 323 | return 5 324 | case val < (1 << 48): 325 | return 6 326 | case val < (1 << 56): 327 | return 7 328 | } 329 | return 8 330 | } 331 | 332 | func errNoBytes() error { 333 | return fmt.Errorf("value is not of type bytes") 334 | } 335 | 336 | func errNoArray() error { 337 | return fmt.Errorf("value is not of type array") 338 | } 339 | -------------------------------------------------------------------------------- /fuzz.go: -------------------------------------------------------------------------------- 1 | package fastrlp 2 | 3 | import ( 4 | "bytes" 5 | "reflect" 6 | 7 | fuzz "github.com/google/gofuzz" 8 | ) 9 | 10 | type FuzzObject interface { 11 | Marshaler 12 | Unmarshaler 13 | } 14 | 15 | type FuzzError struct { 16 | Source, Target interface{} 17 | } 18 | 19 | func (f *FuzzError) Error() string { 20 | return "failed to encode fuzz object" 21 | } 22 | 23 | type FuzzOption func(f *Fuzzer) 24 | 25 | func WithPostHook(fnc func(FuzzObject) error) FuzzOption { 26 | return func(f *Fuzzer) { 27 | f.postHook = fnc 28 | } 29 | } 30 | 31 | func WithDefaults(fnc func(FuzzObject)) FuzzOption { 32 | return func(f *Fuzzer) { 33 | f.defaults = append(f.defaults, fnc) 34 | } 35 | } 36 | 37 | func copyObj(obj interface{}) interface{} { 38 | return reflect.New(reflect.TypeOf(obj).Elem()).Interface() 39 | } 40 | 41 | type Fuzzer struct { 42 | *fuzz.Fuzzer 43 | defaults []func(FuzzObject) 44 | postHook func(FuzzObject) error 45 | } 46 | 47 | func (f *Fuzzer) applyDefaults(obj FuzzObject) FuzzObject { 48 | for _, fn := range f.defaults { 49 | fn(obj) 50 | } 51 | return obj 52 | } 53 | 54 | func Fuzz(num int, base FuzzObject, opts ...FuzzOption) error { 55 | f := &Fuzzer{ 56 | Fuzzer: fuzz.New(), 57 | defaults: []func(FuzzObject){}, 58 | } 59 | for _, opt := range opts { 60 | opt(f) 61 | } 62 | 63 | fuzzImpl := func() error { 64 | // marshal object with the fuzzing 65 | obj := copyObj(base).(FuzzObject) 66 | f.Fuzz(obj) 67 | f.applyDefaults(obj) 68 | 69 | // unmarshal object 70 | obj2 := f.applyDefaults(copyObj(obj).(FuzzObject)) 71 | 72 | data, err := obj.MarshalRLPTo(nil) 73 | if err != nil { 74 | return err 75 | } 76 | if err := obj2.UnmarshalRLP(data); err != nil { 77 | return err 78 | } 79 | 80 | // instead of relying on DeepEqual and issues with zero arrays and so on 81 | // we use the rlp marshal values to compare 82 | data2, err := obj2.MarshalRLPTo(nil) 83 | if err != nil { 84 | return err 85 | } 86 | if !bytes.Equal(data, data2) { 87 | return &FuzzError{Source: obj, Target: obj2} 88 | } 89 | if f.postHook != nil { 90 | if err := f.postHook(obj2); err != nil { 91 | return err 92 | } 93 | } 94 | return nil 95 | } 96 | 97 | for i := 0; i < num; i++ { 98 | if err := fuzzImpl(); err != nil { 99 | return err 100 | } 101 | } 102 | return nil 103 | } 104 | -------------------------------------------------------------------------------- /fuzz_test.go: -------------------------------------------------------------------------------- 1 | package fastrlp 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | ) 7 | 8 | func TestFuzzFramework(t *testing.T) { 9 | obj := &Simple{} 10 | if err := Fuzz(100, obj); err != nil { 11 | t.Fatal(err) 12 | } 13 | } 14 | 15 | type Simple struct { 16 | Data1 []byte 17 | Data2 [][]byte 18 | Data3 uint64 19 | } 20 | 21 | func (s *Simple) MarshalRLPTo(dst []byte) ([]byte, error) { 22 | return MarshalRLP(s) 23 | } 24 | 25 | func (s *Simple) MarshalRLPWith(ar *Arena) (*Value, error) { 26 | vv := ar.NewArray() 27 | 28 | // Data1 29 | if len(s.Data1) == 0 { 30 | vv.Set(ar.NewNull()) 31 | } else { 32 | vv.Set(ar.NewBytes(s.Data1)) 33 | } 34 | 35 | // Data2 36 | if len(s.Data2) == 0 { 37 | vv.Set(ar.NewNullArray()) 38 | } else { 39 | committed := ar.NewArray() 40 | for _, a := range s.Data2 { 41 | if len(a) == 0 { 42 | committed.Set(ar.NewNull()) 43 | } else { 44 | committed.Set(ar.NewBytes(a)) 45 | } 46 | } 47 | vv.Set(committed) 48 | } 49 | 50 | // Data3 51 | vv.Set(ar.NewUint(s.Data3)) 52 | 53 | return vv, nil 54 | } 55 | 56 | func (s *Simple) UnmarshalRLP(buf []byte) error { 57 | return UnmarshalRLP(buf, s) 58 | } 59 | 60 | func (s *Simple) UnmarshalRLPWith(v *Value) error { 61 | elems, err := v.GetElems() 62 | if err != nil { 63 | return err 64 | } 65 | if num := len(elems); num != 3 { 66 | return fmt.Errorf("not enough elements to decode extra, expected 3 but found %d", num) 67 | } 68 | 69 | // Data1 70 | { 71 | if s.Data1, err = elems[0].GetBytes(s.Data1); err != nil { 72 | return err 73 | } 74 | } 75 | 76 | // Data2 77 | { 78 | vals, err := elems[1].GetElems() 79 | if err != nil { 80 | return fmt.Errorf("list expected for committed") 81 | } 82 | if len(vals) == 0 { 83 | s.Data2 = nil 84 | } else { 85 | s.Data2 = make([][]byte, len(vals)) 86 | for indx, val := range vals { 87 | if s.Data2[indx], err = val.GetBytes(s.Data2[indx]); err != nil { 88 | return err 89 | } 90 | } 91 | } 92 | } 93 | 94 | // Data3 95 | if s.Data3, err = elems[2].GetUint64(); err != nil { 96 | return err 97 | } 98 | 99 | return nil 100 | } 101 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/umbracle/fastrlp 2 | 3 | go 1.18 4 | 5 | require ( 6 | github.com/google/gofuzz v1.2.0 7 | golang.org/x/crypto v0.0.0-20201221181555-eec23a3978ad 8 | ) 9 | 10 | require golang.org/x/sys v0.0.0-20191026070338-33540a1f6037 // indirect 11 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0= 2 | github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= 3 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 4 | golang.org/x/crypto v0.0.0-20201221181555-eec23a3978ad h1:DN0cp81fZ3njFcrLCytUHRSUkqBjfTo4Tx9RJTWs0EY= 5 | golang.org/x/crypto v0.0.0-20201221181555-eec23a3978ad/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I= 6 | golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 7 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 8 | golang.org/x/sys v0.0.0-20191026070338-33540a1f6037 h1:YyJpGZS1sBuBCzLAR1VEpK193GlqGZbnPFnPV/5Rsb4= 9 | golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 10 | golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= 11 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 12 | -------------------------------------------------------------------------------- /interface.go: -------------------------------------------------------------------------------- 1 | package fastrlp 2 | 3 | // Marshaler is the interface implemented by types that can marshal themselves into valid RLP messages. 4 | type Marshaler interface { 5 | MarshalRLPTo(dst []byte) ([]byte, error) 6 | MarshalRLPWith(a *Arena) (*Value, error) 7 | } 8 | 9 | // Unmarshaler is the interface implemented by types that can unmarshal a RLP description of themselves 10 | type Unmarshaler interface { 11 | UnmarshalRLP(buf []byte) error 12 | UnmarshalRLPWith(v *Value) error 13 | } 14 | 15 | // MarshalRLP marshals an RLP object 16 | func MarshalRLP(m Marshaler) ([]byte, error) { 17 | ar := &Arena{} 18 | v, err := m.MarshalRLPWith(ar) 19 | if err != nil { 20 | return nil, err 21 | } 22 | return v.MarshalTo(nil), nil 23 | } 24 | 25 | // UnmarshalRLP unmarshals an RLP object 26 | func UnmarshalRLP(buf []byte, m Unmarshaler) error { 27 | p := &Parser{} 28 | v, err := p.Parse(buf) 29 | if err != nil { 30 | return err 31 | } 32 | if err := m.UnmarshalRLPWith(v); err != nil { 33 | return err 34 | } 35 | return nil 36 | } 37 | -------------------------------------------------------------------------------- /keccak.go: -------------------------------------------------------------------------------- 1 | package fastrlp 2 | 3 | import ( 4 | "hash" 5 | 6 | "golang.org/x/crypto/sha3" 7 | ) 8 | 9 | type hashImpl interface { 10 | hash.Hash 11 | Read(b []byte) (int, error) 12 | } 13 | 14 | // Keccak is the sha256 keccak hash 15 | type Keccak struct { 16 | buf []byte // buffer to store intermediate rlp marshal values 17 | tmp []byte 18 | hash hashImpl 19 | } 20 | 21 | // Write implements the hash interface 22 | func (k *Keccak) Write(b []byte) (int, error) { 23 | return k.hash.Write(b) 24 | } 25 | 26 | // Reset implements the hash interface 27 | func (k *Keccak) Reset() { 28 | k.buf = k.buf[:0] 29 | k.hash.Reset() 30 | } 31 | 32 | // Read hashes the content and returns the intermediate buffer. 33 | func (k *Keccak) Read() []byte { 34 | k.hash.Read(k.tmp) 35 | return k.tmp 36 | } 37 | 38 | // Sum implements the hash interface 39 | func (k *Keccak) Sum(dst []byte) []byte { 40 | k.hash.Read(k.tmp) 41 | dst = append(dst, k.tmp[:]...) 42 | return dst 43 | } 44 | 45 | func newKeccak(hash hashImpl) *Keccak { 46 | return &Keccak{ 47 | hash: hash, 48 | tmp: make([]byte, hash.Size()), 49 | } 50 | } 51 | 52 | func NewKeccak256() *Keccak { 53 | return newKeccak(sha3.NewLegacyKeccak256().(hashImpl)) 54 | } 55 | -------------------------------------------------------------------------------- /parser.go: -------------------------------------------------------------------------------- 1 | package fastrlp 2 | 3 | import ( 4 | "encoding/binary" 5 | "fmt" 6 | ) 7 | 8 | // Parser is a RLP parser 9 | type Parser struct { 10 | buf []byte 11 | c cache 12 | k *Keccak 13 | } 14 | 15 | // Parse parses a complete rlp encoding 16 | func (p *Parser) Parse(b []byte) (*Value, error) { 17 | p.c.reset() 18 | p.buf = append(p.buf[:0], b...) 19 | 20 | v, _, err := parseValue(p.buf, &p.c) 21 | if err != nil { 22 | return nil, fmt.Errorf("cannot parse RLP: %s", err) 23 | } 24 | return v, nil 25 | } 26 | 27 | // Raw returns the raw bytes of the value 28 | func (p *Parser) Raw(v *Value) []byte { 29 | return p.buf[v.i : v.i+v.fullLen()] 30 | } 31 | 32 | // Hash performs a keccak hash of the rlp value 33 | func (p *Parser) Hash(dst []byte, v *Value) []byte { 34 | if p.k == nil { 35 | p.k = NewKeccak256() 36 | } 37 | p.k.Reset() 38 | p.k.Write(p.Raw(v)) 39 | return p.k.Sum(dst) 40 | } 41 | 42 | func parseValue(b []byte, c *cache) (*Value, []byte, error) { 43 | if len(b) == 0 { 44 | return nil, b, fmt.Errorf("cannot parse empty string") 45 | } 46 | 47 | cur := b[0] 48 | if cur < 0x80 { 49 | v := c.getValue() 50 | v.t = TypeBytes 51 | v.b = b[:1] 52 | v.l = 1 53 | v.i = c.indx 54 | c.indx++ 55 | return v, b[1:], nil 56 | } 57 | if cur < 0xB8 { 58 | v, tail, err := parseBytes(b[1:], 0, uint64(cur-0x80), c) 59 | if err != nil { 60 | return nil, tail, fmt.Errorf("cannot parse short bytes: %s", err) 61 | } 62 | if v.l == 1 && v.b[0] < 128 { 63 | return nil, nil, fmt.Errorf("bad size") 64 | } 65 | return v, tail, nil 66 | } 67 | if cur < 0xC0 { 68 | intSize := int(cur - 0xB7) 69 | if len(b) < intSize+1 { 70 | return nil, nil, fmt.Errorf("bad size") 71 | } 72 | size := readUint(b[1:intSize+1], c.buf[:]) 73 | if size < 56 { 74 | return nil, nil, fmt.Errorf("bad size") 75 | } 76 | v, tail, err := parseBytes(b[intSize+1:], uint64(intSize), size, c) 77 | if err != nil { 78 | return nil, tail, fmt.Errorf("cannot parse long bytes: %s", err) 79 | } 80 | return v, tail, nil 81 | } 82 | if cur < 0xF8 { 83 | v, tail, err := parseList(b[1:], 0, int(cur-0xC0), c) 84 | if err != nil { 85 | return nil, tail, fmt.Errorf("cannot parse short bytes: %s", err) 86 | } 87 | return v, tail, nil 88 | } 89 | 90 | intSize := int(cur - 0xF7) 91 | if len(b) < intSize+1 { 92 | return nil, nil, fmt.Errorf("bad size") 93 | } 94 | size := readUint(b[1:intSize+1], c.buf[:]) 95 | if size < 56 { 96 | return nil, nil, fmt.Errorf("bad size") 97 | } 98 | v, tail, err := parseList(b[intSize+1:], intSize, int(size), c) 99 | if err != nil { 100 | return nil, tail, fmt.Errorf("cannot parse long array: %s", err) 101 | } 102 | return v, tail, nil 103 | } 104 | 105 | func parseBytes(b []byte, bytes uint64, size uint64, c *cache) (*Value, []byte, error) { 106 | if size > uint64(len(b)) { 107 | return nil, nil, fmt.Errorf("length is not enough") 108 | } 109 | 110 | v := c.getValue() 111 | v.t = TypeBytes 112 | v.b = b[:size] 113 | v.l = uint64(size) 114 | v.i = c.indx 115 | 116 | c.indx += bytes + size + 1 117 | return v, b[size:], nil 118 | } 119 | 120 | func parseList(b []byte, bytes int, size int, c *cache) (*Value, []byte, error) { 121 | a := c.getValue() 122 | a.t = TypeArray 123 | a.a = a.a[:0] 124 | a.l = uint64(size) 125 | a.i = c.indx 126 | 127 | var v *Value 128 | var err error 129 | 130 | c.indx += uint64(bytes) + 1 131 | for size > 0 { 132 | pre := len(b) 133 | v, b, err = parseValue(b, c) 134 | if err != nil { 135 | return nil, b, fmt.Errorf("cannot parse array value: %s", err) 136 | } 137 | a.a = append(a.a, v) 138 | size -= pre - len(b) 139 | } 140 | if size < 0 { 141 | return nil, nil, fmt.Errorf("bad ending") 142 | } 143 | return a, b, nil 144 | } 145 | 146 | func readUint(b []byte, buf []byte) uint64 { 147 | size := len(b) 148 | ini := 8 - size 149 | for i := 0; i < ini; i++ { 150 | buf[i] = 0 151 | } 152 | copy(buf[ini:], b[:size]) 153 | return binary.BigEndian.Uint64(buf[:]) 154 | } 155 | -------------------------------------------------------------------------------- /parser_test.go: -------------------------------------------------------------------------------- 1 | package fastrlp 2 | 3 | import ( 4 | "bytes" 5 | "encoding/hex" 6 | "math/rand" 7 | "testing" 8 | "time" 9 | ) 10 | 11 | func TestEncodingRawRandom(t *testing.T) { 12 | for i := 0; i < 10000; i++ { 13 | v0 := generateRandom() 14 | buf := v0.MarshalTo(nil) 15 | 16 | p := &Parser{} 17 | v, err := p.Parse(buf) 18 | if err != nil { 19 | t.Fatal(err) 20 | } 21 | 22 | buf1 := v.MarshalTo(nil) 23 | if !bytes.Equal(buf, buf1) { 24 | t.Fatal("bad") 25 | } 26 | if !checkRaw(p, v, v0) { 27 | t.Fatal("bad") 28 | } 29 | } 30 | } 31 | 32 | func checkRaw(p *Parser, v *Value, v0 *Value) bool { 33 | if v.Type() == TypeArray { 34 | elems, err := v.GetElems() 35 | if err != nil { 36 | panic(err) 37 | } 38 | for indx, elem := range elems { 39 | if !checkRaw(p, elem, v0.Get(indx)) { 40 | return false 41 | } 42 | } 43 | } 44 | buf := p.Raw(v) 45 | if !bytes.Equal(buf, v.MarshalTo(nil)) { 46 | return false 47 | } 48 | return true 49 | } 50 | 51 | func randomInt(min, max int) int { 52 | return min + rand.Intn(max-min) 53 | } 54 | 55 | func generateRandom() *Value { 56 | rand.Seed(time.Now().UTC().UnixNano()) 57 | return generateRandomImpl(&Arena{}, 0) 58 | } 59 | 60 | func generateRandomImpl(a *Arena, depth uint) *Value { 61 | if randomInt(0, 10) < 5 || depth > 2 { 62 | // value 63 | buf := make([]byte, randomInt(1, 100)) 64 | rand.Read(buf) 65 | return a.NewBytes(buf) 66 | } 67 | // array 68 | v := a.NewArray() 69 | for i := 0; i < randomInt(1, 5); i++ { 70 | v.Set(generateRandomImpl(a, depth+1)) 71 | } 72 | return v 73 | } 74 | 75 | func TestInvalidRlp(t *testing.T) { 76 | // cases from the official spec 77 | 78 | cases := []string{ 79 | "bf0f000000000000021111", 80 | "ff0f000000000000021111", 81 | "f80180", 82 | "f80100", 83 | "b9002100dc2b275d0f74e8a53e6f4ec61b27f24278820be3f82ea2110e582081b0565df0", 84 | "f861f83eb9002100dc2b275d0f74e8a53e6f4ec61b27f24278820be3f82ea2110e582081b0565df027b90015002d5ef8325ae4d034df55d4b58d0dfba64d61ddd17be00000b9001a00dae30907045a2f66fa36f2bb8aa9029cbb0b8a7b3b5c435ab331", 85 | "8100", 86 | "8101", 87 | "817F", 88 | } 89 | 90 | p := &Parser{} 91 | for _, c := range cases { 92 | buf, err := hex.DecodeString(c) 93 | if err != nil { 94 | t.Fatal(err) 95 | } 96 | 97 | if _, err = p.Parse(buf); err == nil { 98 | t.Fatal("it should fail") 99 | } 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /pool.go: -------------------------------------------------------------------------------- 1 | package fastrlp 2 | 3 | import ( 4 | "sync" 5 | ) 6 | 7 | // DefaultParserPool is a default ParserPool 8 | var DefaultParserPool ParserPool 9 | 10 | // ParserPool may be used for pooling Parsers for similarly typed RLPs. 11 | type ParserPool struct { 12 | pool sync.Pool 13 | } 14 | 15 | // Get acquires a Parser from the pool. 16 | func (pp *ParserPool) Get() *Parser { 17 | v := pp.pool.Get() 18 | if v == nil { 19 | return &Parser{} 20 | } 21 | return v.(*Parser) 22 | } 23 | 24 | // Put releases the parser to the pool. 25 | func (pp *ParserPool) Put(p *Parser) { 26 | pp.pool.Put(p) 27 | } 28 | 29 | // DefaultArenaPool is a default ArenaPool 30 | var DefaultArenaPool ArenaPool 31 | 32 | // ArenaPool may be used for pooling Arenas for similarly typed RLPs. 33 | type ArenaPool struct { 34 | pool sync.Pool 35 | } 36 | 37 | // Get acquires an Arena from the pool. 38 | func (ap *ArenaPool) Get() *Arena { 39 | v := ap.pool.Get() 40 | if v == nil { 41 | return &Arena{} 42 | } 43 | return v.(*Arena) 44 | } 45 | 46 | // Put releases an Arena to the pool. 47 | func (ap *ArenaPool) Put(a *Arena) { 48 | a.Reset() 49 | ap.pool.Put(a) 50 | } 51 | --------------------------------------------------------------------------------