ciri-rlp 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: d771c9588988901adee213e5700b8b100bc4b1b80adafa6c6c28e24df094fca4
4
+ data.tar.gz: 0d01028c1512e74539c428636f8488b111be6084121301e7c96f979d52e7cb73
5
+ SHA512:
6
+ metadata.gz: 2c18f633b26c0df808aac1da26702f6c2bedc783e141e9c30d38c1608461815c01a3f10e6e6514c4092baffb796c2718af9b11d91079c79a5c09f830602402e6
7
+ data.tar.gz: 3d9d8687593c7aaea68712abce4e558bfaabea2218721aa34a6087b8c4699ba2515ff49e164d415423a1f704a259cf6180ef78b09386193a0491976994947d32
data/.gitignore ADDED
@@ -0,0 +1,11 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+ # rspec failure tracking
11
+ .rspec_status
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.travis.yml ADDED
@@ -0,0 +1,5 @@
1
+ sudo: false
2
+ language: ruby
3
+ rvm:
4
+ - 2.5.0
5
+ before_install: gem install bundler -v 1.16.1
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at jjyruby@gmail.com. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [http://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: http://contributor-covenant.org
74
+ [version]: http://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,6 @@
1
+ source "https://rubygems.org"
2
+
3
+ git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
4
+
5
+ # Specify your gem's dependencies in ciri-rlp.gemspec
6
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2018 Jiang Jinyang
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,98 @@
1
+ # Ciri::RLP
2
+
3
+ The Ruby RLP serialization library.
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ ```ruby
10
+ gem 'ciri-rlp'
11
+ ```
12
+
13
+ And then execute:
14
+
15
+ $ bundle
16
+
17
+ Or install it yourself as:
18
+
19
+ $ gem install ciri-rlp
20
+
21
+ ## Usage
22
+
23
+ Simple use:
24
+
25
+ ```ruby
26
+ # encode
27
+ Ciri::RLP.encode(3)
28
+ Ciri::RLP.encode(["cat", 1, "dog", 3])
29
+ # decode
30
+ Ciri::RLP.decode("rlp encoded content")
31
+ ```
32
+
33
+ Structure:
34
+ ```ruby
35
+ # declare a RLP structure
36
+ class Doge
37
+ include Ciri::RLP::Serializable
38
+
39
+ # RLP is a low level encoding format, only support string(bytes) and list.
40
+ # so we use a list to present structure data
41
+ # we also need to declare column type clearly if column is not string
42
+ schema [
43
+ :name,
44
+ {age: Integer}, # declare age is a Integer type
45
+ :gender,
46
+ {has_master: Ciri::RLP::Bool} # dechare bool
47
+ ]
48
+ end
49
+
50
+ doge = Doge.new(name: 'neo doge', age: 5, gender: "boy", has_master: false)
51
+ # use auto generated encode method
52
+ encoded = Doge.rlp_encode(doge)
53
+ Doge.rlp_decode(encoded) == doge
54
+ # => true
55
+ ```
56
+
57
+ Customize:
58
+ ```ruby
59
+ class DogeList
60
+ attr_reader :doges
61
+
62
+ def initialize(doges)
63
+ @doges = doges
64
+ end
65
+
66
+ # provide two class methods: rlp_encode and rlp_decode to customize RLP behaviour
67
+ # ciri-rlp will consider duck-typing and invoke those methods
68
+ # customize RLP class can be member of other RLP struct
69
+ def self.rlp_encode(doge_list)
70
+ # [Doge] represent the encode data is an array of Doge
71
+ Ciri::RLP.encode(doge_list.doges, [Doge])
72
+ end
73
+
74
+ def self.rlp_decode(encoded)
75
+ doges = Ciri::RLP.decode(encoded, [Doge])
76
+ DogeList.new(doges)
77
+ end
78
+ end
79
+
80
+ ```
81
+
82
+ ## Development
83
+
84
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
85
+
86
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
87
+
88
+ ## Contributing
89
+
90
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/ciri-rlp. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
91
+
92
+ ## License
93
+
94
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
95
+
96
+ ## Code of Conduct
97
+
98
+ Everyone interacting in the Ciri::Rlp project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/ciri-rlp/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,6 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "ciri/rlp"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
data/ciri-rlp.gemspec ADDED
@@ -0,0 +1,28 @@
1
+
2
+ lib = File.expand_path("../lib", __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require "ciri/rlp/version"
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "ciri-rlp"
8
+ spec.version = Ciri::Rlp::VERSION
9
+ spec.authors = ["Jiang Jinyang"]
10
+ spec.email = ["jjyruby@gmail.com"]
11
+
12
+ spec.summary = %q{The RLP serialization library.}
13
+ spec.description = %q{Provide simple and structure RLP serialization.}
14
+ spec.homepage = "https://github.com/ciri-ethereum/ciri"
15
+ spec.license = "MIT"
16
+
17
+ spec.files = `git ls-files -z`.split("\x0").reject do |f|
18
+ f.match(%r{^(test|spec|features)/})
19
+ end
20
+ spec.bindir = "exe"
21
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
22
+ spec.require_paths = ["lib"]
23
+
24
+ spec.add_dependency "ciri-utils", "~> 0.1.0"
25
+ spec.add_development_dependency "bundler", "~> 1.16"
26
+ spec.add_development_dependency "rake", "~> 10.0"
27
+ spec.add_development_dependency "rspec", "~> 3.0"
28
+ end
@@ -0,0 +1,144 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Copyright (c) 2018, by Jiang Jinyang. <https://justjjy.com>
4
+ #
5
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ # of this software and associated documentation files (the "Software"), to deal
7
+ # in the Software without restriction, including without limitation the rights
8
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ # copies of the Software, and to permit persons to whom the Software is
10
+ # furnished to do so, subject to the following conditions:
11
+ #
12
+ # The above copyright notice and this permission notice shall be included in
13
+ # all copies or substantial portions of the Software.
14
+ #
15
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ # THE SOFTWARE.
22
+
23
+
24
+ require 'stringio'
25
+
26
+ module Ciri
27
+ module RLP
28
+ module Decode
29
+
30
+ # Decode input from rlp encoding, only produce string or array
31
+ #
32
+ # Examples:
33
+ #
34
+ # Ciri::RLP.decode(input)
35
+ #
36
+ def decode(input, type = Raw)
37
+ decode_with_type(input, type)
38
+ end
39
+
40
+ # Use this method after RLP.decode, decode values from string or array to specific types
41
+ # see Ciri::RLP::Serializable::TYPES for supported types
42
+ #
43
+ # Examples:
44
+ #
45
+ # item = Ciri::RLP.decode(encoded_text)
46
+ # decode_with_type(item, Integer)
47
+ #
48
+ def decode_with_type(s, type)
49
+ s = StringIO.new(s) if s.is_a?(String)
50
+ if type == Integer
51
+ item = s.read(1)
52
+ if item.nil?
53
+ raise InvalidValueError.new "invalid bool value nil"
54
+ elsif item == "\x80".b || item.empty?
55
+ 0
56
+ elsif item.ord < 0x80
57
+ item.ord
58
+ else
59
+ size = item[0].ord - 0x80
60
+ Ciri::Utils.big_endian_decode(s.read(size))
61
+ end
62
+ elsif type == Bool
63
+ item = s.read(1)
64
+ if item == Bool::ENCODED_TRUE
65
+ true
66
+ elsif item == Bool::ENCODED_FALSE
67
+ false
68
+ else
69
+ raise InvalidValueError.new "invalid bool value #{item}"
70
+ end
71
+ elsif type.is_a?(Class) && type.respond_to?(:rlp_decode)
72
+ type.rlp_decode(s)
73
+ elsif type.is_a?(Array)
74
+ decode_list(s) do |list, s2|
75
+ i = 0
76
+ until s2.eof?
77
+ t = type.size > i ? type[i] : type[-1]
78
+ list << decode_with_type(s2, t)
79
+ i += 1
80
+ end
81
+ end
82
+ elsif type == Raw
83
+ decode_stream(s)
84
+ else
85
+ raise RLP::InvalidValueError.new "unknown type #{type}"
86
+ end
87
+ rescue
88
+ STDERR.puts "when decoding #{s} into #{type}"
89
+ raise
90
+ end
91
+
92
+ protected
93
+
94
+ def decode_list(s, first_char = nil, &decoder)
95
+ s = StringIO.new(s) if s.is_a?(String)
96
+ c = first_char || s.read(1)
97
+ list = []
98
+
99
+ sub_s = case c.ord
100
+ when 0xc0..0xf7
101
+ length = c.ord - 0xc0
102
+ s.read(length)
103
+ when 0xf8..0xff
104
+ length_binary = s.read(c.ord - 0xf7)
105
+ length = int_from_binary(length_binary)
106
+ s.read(length)
107
+ else
108
+ raise InvalidValueError.new("invalid char #{c}")
109
+ end
110
+
111
+ decoder.call(list, StringIO.new(sub_s))
112
+ list
113
+ end
114
+
115
+ private
116
+
117
+ def decode_stream(s)
118
+ c = s.read(1)
119
+ case c.ord
120
+ when 0x00..0x7f
121
+ c
122
+ when 0x80..0xb7
123
+ length = c.ord - 0x80
124
+ s.read(length)
125
+ when 0xb8..0xbf
126
+ length_binary = s.read(c.ord - 0xb7)
127
+ length = int_from_binary(length_binary)
128
+ s.read(length)
129
+ else
130
+ decode_list(s, c) do |list, s2|
131
+ until s2.eof?
132
+ list << decode_stream(s2)
133
+ end
134
+ end
135
+ end
136
+ end
137
+
138
+ def int_from_binary(input)
139
+ Ciri::Utils.big_endian_decode(input)
140
+ end
141
+
142
+ end
143
+ end
144
+ end
@@ -0,0 +1,140 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Copyright (c) 2018, by Jiang Jinyang. <https://justjjy.com>
4
+ #
5
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ # of this software and associated documentation files (the "Software"), to deal
7
+ # in the Software without restriction, including without limitation the rights
8
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ # copies of the Software, and to permit persons to whom the Software is
10
+ # furnished to do so, subject to the following conditions:
11
+ #
12
+ # The above copyright notice and this permission notice shall be included in
13
+ # all copies or substantial portions of the Software.
14
+ #
15
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ # THE SOFTWARE.
22
+
23
+
24
+ module Ciri
25
+ module RLP
26
+ module Encode
27
+
28
+ class InputOverflow < StandardError
29
+ end
30
+
31
+ # Encode input to rlp encoding
32
+ #
33
+ # Examples:
34
+ #
35
+ # Ciri::RLP.encode("hello world")
36
+ #
37
+ def encode(input, type = nil)
38
+ type ? encode_with_type(input, type) : encode_simple(input)
39
+ end
40
+
41
+ def encode_simple(input)
42
+ if input.is_a?(Array)
43
+ encode_list(input) {|i| encode_simple(i)}
44
+ elsif input.is_a?(Integer)
45
+ encode_with_type(input, Integer)
46
+ elsif input.class.respond_to?(:rlp_encode)
47
+ input.class.rlp_encode(input)
48
+ else
49
+ encode_with_type(input, Raw)
50
+ end
51
+ end
52
+
53
+ # Use this method before RLP.encode, this method encode ruby objects to rlp friendly format, string or array.
54
+ # see Ciri::RLP::Serializable::TYPES for supported types
55
+ #
56
+ # Examples:
57
+ #
58
+ # item = Ciri::RLP.encode_with_type(number, :int, zero: "\x00".b)
59
+ # encoded_text = Ciri::RLP.encode(item)
60
+ #
61
+ def encode_with_type(item, type, zero: '')
62
+ if type == Integer
63
+ if item == 0
64
+ "\x80".b
65
+ elsif item < 0x80
66
+ Ciri::Utils.big_endian_encode(item, zero)
67
+ else
68
+ buf = Ciri::Utils.big_endian_encode(item, zero)
69
+ [0x80 + buf.size].pack("c*") + buf
70
+ end
71
+ elsif type == Bool
72
+ item ? Bool::ENCODED_TRUE : Bool::ENCODED_FALSE
73
+ elsif type.is_a?(Class) && type.respond_to?(:rlp_encode)
74
+ type.rlp_encode(item)
75
+ elsif type.is_a?(Array)
76
+ if type.size == 1 # array type
77
+ encode_list(item) {|i| encode_with_type(i, type[0])}
78
+ else # unknown
79
+ raise RLP::InvalidValueError.new "type size should be 1, got #{type}"
80
+ end
81
+ elsif type == Raw
82
+ encode_raw(item)
83
+ else
84
+ raise RLP::InvalidValueError.new "unknown type #{type}"
85
+ end
86
+ rescue
87
+ STDERR.puts "when encoding #{Utils.to_hex item.to_s} into #{type}"
88
+ raise
89
+ end
90
+
91
+ protected
92
+
93
+ def encode_raw(input)
94
+ result = if input.is_a?(String)
95
+ encode_string(input)
96
+ elsif input.is_a?(Array)
97
+ encode_list(input) {|item| encode(item)}
98
+ else
99
+ raise ArgumentError.new("input must be a String or Array, #{input.inspect}")
100
+ end
101
+ result.b
102
+ end
103
+
104
+ def encode_string(input)
105
+ length = input.length
106
+ if length == 1 && input.ord < 0x80
107
+ input
108
+ elsif length < 56
109
+ to_binary(0x80 + length) + input
110
+ elsif length < 256 ** 8
111
+ binary_length = to_binary(length)
112
+ to_binary(0xb7 + binary_length.size) + binary_length + input
113
+ else
114
+ raise InputOverflow.new("input length #{input.size} is too long")
115
+ end
116
+ end
117
+
118
+ def encode_list(input, &encoder)
119
+ input ||= [] # allow nil list
120
+ output = encoder ? input.map {|item| encoder.call(item)}.join : input.join
121
+ length = output.length
122
+ if length < 56
123
+ to_binary(0xc0 + length) + output
124
+ elsif length < 256 ** 8
125
+ binary_length = to_binary(length)
126
+ to_binary(0xf7 + binary_length.size) + binary_length + output
127
+ else
128
+ raise InputOverflow.new("input length #{input.size} is too long")
129
+ end
130
+ end
131
+
132
+ private
133
+
134
+ def to_binary(n)
135
+ Ciri::Utils.big_endian_encode(n)
136
+ end
137
+
138
+ end
139
+ end
140
+ end
@@ -0,0 +1,241 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Copyright (c) 2018, by Jiang Jinyang. <https://justjjy.com>
4
+ #
5
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ # of this software and associated documentation files (the "Software"), to deal
7
+ # in the Software without restriction, including without limitation the rights
8
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ # copies of the Software, and to permit persons to whom the Software is
10
+ # furnished to do so, subject to the following conditions:
11
+ #
12
+ # The above copyright notice and this permission notice shall be included in
13
+ # all copies or substantial portions of the Software.
14
+ #
15
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ # THE SOFTWARE.
22
+
23
+
24
+ require 'ciri/utils'
25
+
26
+ module Ciri
27
+ module RLP
28
+
29
+ # represent bool types: true | false
30
+ class Bool
31
+ ENCODED_TRUE = Ciri::Utils.big_endian_encode(0x01)
32
+ ENCODED_FALSE = Ciri::Utils.big_endian_encode(0x80)
33
+ end
34
+
35
+ # represent RLP raw types, binary or array
36
+ class Raw
37
+ end
38
+
39
+ # Serializable module allow ruby objects serialize/deserialize to or from RLP encoding.
40
+ # See Ciri::RLP::Serializable::TYPES for supported type.
41
+ #
42
+ # schema method define ordered data structure for class, and determine how to encoding objects.
43
+ #
44
+ # schema follow `{attr_name: type}` format,
45
+ # if attr is raw type(string or array of string), you can just use `:attr_name` to define it
46
+ # schema simple types include Integer, Bool, String, Array...
47
+ #
48
+ # schema also support complex types: array and serializable.
49
+ #
50
+ # array types represented as `{attr_name: [type]}`, for example: `{bills: [Integer]}` means value of bill attr is an array of integer
51
+ # serializable type represent value of attr is a RLP serializable object
52
+ #
53
+ #
54
+ # Examples:
55
+ #
56
+ # class AuthMsgV4
57
+ # include Ciri::RLP::Serializable
58
+ #
59
+ # # define schema
60
+ # schema [
61
+ # :signature, # raw type: string
62
+ # {initiator_pubkey: MySerializableKey}, # this attr is a RLP serializable object
63
+ # {nonce: [Integer]},
64
+ # {version: Integer}
65
+ # ]
66
+ #
67
+ # # default values
68
+ # default_data(got_plain: false)
69
+ # end
70
+ #
71
+ # msg = AuthMsgV4.new(signature: "\x00", initiator_pubkey: my_pubkey, nonce: [1, 2, 3], version: 4)
72
+ # encoded = msg.rlp_encode
73
+ # msg2 = AuthMsgV4.rlp_decode(encoded)
74
+ # msg == msg2 # true
75
+ #
76
+ module Serializable
77
+ # nil represent RLP raw value(string or array of string)
78
+ TYPES = [Raw, Integer, Bool].map {|key| [key, true]}.to_h.freeze
79
+
80
+ # Schema specific columns types of classes, normally you should not use Serializable::Schema directly
81
+ #
82
+ class Schema
83
+ include Encode
84
+ include Decode
85
+
86
+ class InvalidSchemaError < StandardError
87
+ end
88
+
89
+ # keys return data columns array
90
+ attr_reader :keys
91
+
92
+ KeySchema = Struct.new(:type, :options, keyword_init: true)
93
+
94
+ def initialize(schema)
95
+ keys = []
96
+ @_schema = {}
97
+
98
+ schema.each do |key|
99
+ if key.is_a?(Hash)
100
+ options = [:optional].map {|o| [o, key.delete(o)]}.to_h
101
+ raise InvalidSchemaError.new("include unknown options #{key}") unless key.size == 1
102
+ key, type = key.to_a[0]
103
+ else
104
+ options = {}
105
+ type = Raw
106
+ end
107
+ raise InvalidSchemaError.new("missing type #{type} for key #{key}") unless check_key_type(type)
108
+ keys << key
109
+ @_schema[key] = KeySchema.new(type: type, options: options)
110
+ end
111
+
112
+ @_schema.freeze
113
+ @keys = keys.freeze
114
+ end
115
+
116
+ # Get column type, see Serializable::TYPES for supported type
117
+ def [](key)
118
+ @_schema[key]
119
+ end
120
+
121
+ # Validate data, data is a Hash
122
+ def validate!(data)
123
+ keys.each do |key|
124
+ raise InvalidSchemaError.new("missing key #{key}") unless data.key?(key)
125
+ end
126
+ end
127
+
128
+ def rlp_encode(data, skip_keys: nil, white_list_keys: nil)
129
+ # pre-encode, encode data to rlp compatible format(only string or array)
130
+ used_keys = if white_list_keys
131
+ white_list_keys
132
+ elsif skip_keys
133
+ keys - skip_keys
134
+ else
135
+ keys
136
+ end
137
+ data_list = []
138
+ used_keys.each do |key|
139
+ value = data[key]
140
+ next if value.nil? && self[key].options[:optional]
141
+ data_list << encode_with_type(value, self[key].type)
142
+ end
143
+ encode_list(data_list)
144
+ end
145
+
146
+ def rlp_decode(input)
147
+ values = decode_list(input) do |list, stream|
148
+ keys.each do |key|
149
+ # decode data by type
150
+ next if stream.eof? && self[key].options[:optional]
151
+ list << decode_with_type(stream, self[key].type)
152
+ end
153
+ end
154
+ # convert to key value hash
155
+ keys.zip(values).to_h
156
+ end
157
+
158
+ private
159
+
160
+ def check_key_type(type)
161
+ return true if TYPES.key?(type)
162
+ return true if type.is_a?(Class) && type.respond_to?(:rlp_decode) && type.respond_to?(:rlp_encode)
163
+
164
+ if type.is_a?(Array) && type.size == 1
165
+ check_key_type(type[0])
166
+ else
167
+ false
168
+ end
169
+ end
170
+ end
171
+
172
+ module ClassMethods
173
+ # Decode object from input
174
+ def rlp_decode(input)
175
+ data = schema.rlp_decode(input)
176
+ self.new(data)
177
+ end
178
+
179
+ # Encode object to rlp encoding string
180
+ def rlp_encode(item, skip_keys: nil, white_list_keys: nil)
181
+ schema.rlp_encode(item.serializable_attributes, skip_keys: skip_keys, white_list_keys: white_list_keys)
182
+ end
183
+
184
+ def schema(data_schema = nil)
185
+ @data_schema ||= Schema.new(data_schema).tap do |schema|
186
+ # define attributes methods
187
+ define_attributes(schema)
188
+ end
189
+ end
190
+
191
+ def default_data(data = nil)
192
+ @default_data ||= data
193
+ end
194
+
195
+ private
196
+
197
+ def define_attributes(schema)
198
+ schema.keys.each do |attribute|
199
+ module_eval <<-ATTR_METHODS
200
+ def #{attribute}
201
+ serializable_attributes[:"#{attribute}"]
202
+ end
203
+
204
+ def #{attribute}=(value)
205
+ serializable_attributes[:"#{attribute}"] = value
206
+ end
207
+ ATTR_METHODS
208
+ end
209
+ end
210
+ end
211
+
212
+ class << self
213
+ def included(base)
214
+ base.send :extend, ClassMethods
215
+ end
216
+ end
217
+
218
+ attr_reader :serializable_attributes
219
+
220
+ def initialize(**data)
221
+ @serializable_attributes = (self.class.default_data || {}).merge(data)
222
+ self.class.schema.validate!(@serializable_attributes)
223
+ end
224
+
225
+ def initialize_copy(orig)
226
+ super
227
+ @serializable_attributes = orig.serializable_attributes.dup
228
+ end
229
+
230
+ # Encode object to rlp encoding string
231
+ def rlp_encode(skip_keys: nil, white_list_keys: nil)
232
+ self.class.rlp_encode(self, skip_keys: skip_keys, white_list_keys: white_list_keys)
233
+ end
234
+
235
+ def ==(other)
236
+ self.class == other.class && serializable_attributes == other.serializable_attributes
237
+ end
238
+
239
+ end
240
+ end
241
+ end
@@ -0,0 +1,5 @@
1
+ module Ciri
2
+ module Rlp
3
+ VERSION = "0.1.0"
4
+ end
5
+ end
data/lib/ciri/rlp.rb ADDED
@@ -0,0 +1,38 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Copyright (c) 2018, by Jiang Jinyang. <https://justjjy.com>
4
+ #
5
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ # of this software and associated documentation files (the "Software"), to deal
7
+ # in the Software without restriction, including without limitation the rights
8
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ # copies of the Software, and to permit persons to whom the Software is
10
+ # furnished to do so, subject to the following conditions:
11
+ #
12
+ # The above copyright notice and this permission notice shall be included in
13
+ # all copies or substantial portions of the Software.
14
+ #
15
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ # THE SOFTWARE.
22
+
23
+ require 'ciri/rlp/version'
24
+ require_relative 'rlp/decode'
25
+ require_relative 'rlp/encode'
26
+ require_relative 'rlp/serializable'
27
+
28
+ module Ciri
29
+ module RLP
30
+
31
+ class InvalidValueError < StandardError
32
+ end
33
+
34
+ extend Encode
35
+ extend Decode
36
+
37
+ end
38
+ end
metadata ADDED
@@ -0,0 +1,116 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: ciri-rlp
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Jiang Jinyang
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2018-07-01 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: ciri-utils
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: 0.1.0
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: 0.1.0
27
+ - !ruby/object:Gem::Dependency
28
+ name: bundler
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '1.16'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '1.16'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rake
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '10.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '10.0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: rspec
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '3.0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '3.0'
69
+ description: Provide simple and structure RLP serialization.
70
+ email:
71
+ - jjyruby@gmail.com
72
+ executables: []
73
+ extensions: []
74
+ extra_rdoc_files: []
75
+ files:
76
+ - ".gitignore"
77
+ - ".rspec"
78
+ - ".travis.yml"
79
+ - CODE_OF_CONDUCT.md
80
+ - Gemfile
81
+ - LICENSE.txt
82
+ - README.md
83
+ - Rakefile
84
+ - bin/console
85
+ - bin/setup
86
+ - ciri-rlp.gemspec
87
+ - lib/ciri/rlp.rb
88
+ - lib/ciri/rlp/decode.rb
89
+ - lib/ciri/rlp/encode.rb
90
+ - lib/ciri/rlp/serializable.rb
91
+ - lib/ciri/rlp/version.rb
92
+ homepage: https://github.com/ciri-ethereum/ciri
93
+ licenses:
94
+ - MIT
95
+ metadata: {}
96
+ post_install_message:
97
+ rdoc_options: []
98
+ require_paths:
99
+ - lib
100
+ required_ruby_version: !ruby/object:Gem::Requirement
101
+ requirements:
102
+ - - ">="
103
+ - !ruby/object:Gem::Version
104
+ version: '0'
105
+ required_rubygems_version: !ruby/object:Gem::Requirement
106
+ requirements:
107
+ - - ">="
108
+ - !ruby/object:Gem::Version
109
+ version: '0'
110
+ requirements: []
111
+ rubyforge_project:
112
+ rubygems_version: 2.7.3
113
+ signing_key:
114
+ specification_version: 4
115
+ summary: The RLP serialization library.
116
+ test_files: []