glueby 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 593ee57bb01d23f91f508e851efa30d3fbbeda69232ebde715abc242fe609f02
4
+ data.tar.gz: 6444c5e75e4fe70f3dca80c65546b340968577c0b7e7a82e21b5b8eb6836ab47
5
+ SHA512:
6
+ metadata.gz: 899894c6b9e24800f562f6360ea00b568c8bd333dccfbde038e9cdff1c75f8fa10e27086737f2df5547710b401a455c5f9adb766a7a27a1b1dbbc9585df6e0d3
7
+ data.tar.gz: bee37a6f3267f476a562f6c2d1c75424d549573d3fd4177b4a0811c1a866e87e7ac0f2f73fdca477814ee9d9fda797b0b6ba423ddd67efedca1ccdb987045022
@@ -0,0 +1,13 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+ Gemfile.lock
10
+
11
+ # rspec failure tracking
12
+ .rspec_status
13
+ .rakeTasks
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
@@ -0,0 +1 @@
1
+ tapyrusrb
@@ -0,0 +1 @@
1
+ 2.7.0
@@ -0,0 +1,6 @@
1
+ ---
2
+ language: ruby
3
+ cache: bundler
4
+ rvm:
5
+ - 2.6.3
6
+ before_install: gem install bundler -v 2.1.4
@@ -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 azuchi@chaintope.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 [https://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: https://contributor-covenant.org
74
+ [version]: https://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,7 @@
1
+ source "https://rubygems.org"
2
+
3
+ # Specify your gem's dependencies in glueby.gemspec
4
+ gemspec
5
+
6
+ gem "rake", "~> 12.0"
7
+ gem "rspec", "~> 3.0"
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2020 Chaintope, Inc.
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.
@@ -0,0 +1,166 @@
1
+ # Glueby
2
+
3
+ Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/glueby`. To experiment with that code, run `bin/console` for an interactive prompt.
4
+
5
+ TODO: Delete this and the text above, and describe your gem
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'glueby'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle install
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install glueby
22
+
23
+ ## Usage
24
+
25
+ ```ruby
26
+
27
+ config = {schema: 'http', host: '127.0.0.1', port: 12381, user: 'user', password: 'pass'}
28
+ Glueby::Contract::RPC.configure(config)
29
+
30
+ timestamp = Glueby::Contract::Timestamp.new(content: "\x01\x02\x03")
31
+ timestamp.save!
32
+ # "a01eace94ce6cdc30f389609de8a7584a4e208ee82fec33a2f5875b7cee47097"
33
+
34
+ ```
35
+
36
+ We can see the timestamp transaction using getrawblockchain command
37
+
38
+ ```bash
39
+ > tapyrus-cli -rpcport=12381 -rpcuser=user -rpcpassword=pass getrawtransaction a01eace94ce6cdc30f389609de8a7584a4e208ee82fec33a2f5875b7cee47097 1
40
+
41
+ {
42
+ "txid": "a01eace94ce6cdc30f389609de8a7584a4e208ee82fec33a2f5875b7cee47097",
43
+ "hash": "a559a84d94cff58619bb735862eb93ff7a3b8fe122a8f2f4c10b7814fb15459a",
44
+ "features": 1,
45
+ "size": 234,
46
+ "vsize": 234,
47
+ "weight": 936,
48
+ "locktime": 0,
49
+ "vin": [
50
+ {
51
+ "txid": "12658e0289da70d43ae3777a174ac8c40f89cbe6564ed6606f197764b3556200",
52
+ "vout": 0,
53
+ "scriptSig": {
54
+ "asm": "3044022067285c57a57fc0d7f64576abbec65639b0f4a8c31b5605eefe881edccb97c62402201ddec93c0c9bf3bb5707757e97e7fa6566c0183b41537e4f9ec46dcfe401864d[ALL] 03b8ad9e3271a20d5eb2b622e455fcffa5c9c90e38b192772b2e1b58f6b442e78d",
55
+ "hex": "473044022067285c57a57fc0d7f64576abbec65639b0f4a8c31b5605eefe881edccb97c62402201ddec93c0c9bf3bb5707757e97e7fa6566c0183b41537e4f9ec46dcfe401864d012103b8ad9e3271a20d5eb2b622e455fcffa5c9c90e38b192772b2e1b58f6b442e78d"
56
+ },
57
+ "sequence": 4294967295
58
+ }
59
+ ],
60
+ "vout": [
61
+ {
62
+ "value": 0.00000000,
63
+ "n": 0,
64
+ "scriptPubKey": {
65
+ "asm": "OP_RETURN 039058c6f2c0cb492c533b0a4d14ef77cc0f78abccced5287d84a1a2011cfb81",
66
+ "hex": "6a20039058c6f2c0cb492c533b0a4d14ef77cc0f78abccced5287d84a1a2011cfb81",
67
+ "type": "nulldata"
68
+ }
69
+ },
70
+ {
71
+ "value": 49.99990000,
72
+ "n": 1,
73
+ "scriptPubKey": {
74
+ "asm": "OP_DUP OP_HASH160 3c0422f624f2503193c7413eff32839b9e151b54 OP_EQUALVERIFY OP_CHECKSIG",
75
+ "hex": "76a9143c0422f624f2503193c7413eff32839b9e151b5488ac",
76
+ "reqSigs": 1,
77
+ "type": "pubkeyhash",
78
+ "addresses": [
79
+ "16ULVva73ZhQiZu9o3njXc3TZ3aSog7FQQ"
80
+ ]
81
+ }
82
+ }
83
+ ],
84
+ "hex": "0100000001006255b36477196f60d64e56e6cb890fc4c84a177a77e33ad470da89028e6512000000006a473044022067285c57a57fc0d7f64576abbec65639b0f4a8c31b5605eefe881edccb97c62402201ddec93c0c9bf3bb5707757e97e7fa6566c0183b41537e4f9ec46dcfe401864d012103b8ad9e3271a20d5eb2b622e455fcffa5c9c90e38b192772b2e1b58f6b442e78dffffffff020000000000000000226a20039058c6f2c0cb492c533b0a4d14ef77cc0f78abccced5287d84a1a2011cfb81f0ca052a010000001976a9143c0422f624f2503193c7413eff32839b9e151b5488ac00000000",
85
+ "blockhash": "d33efc626114f89445d12c27f453c209382a3cb49de132bf978449093f2d2dbb",
86
+ "confirmations": 3,
87
+ "time": 1590822803,
88
+ "blocktime": 1590822803
89
+ }
90
+ ```
91
+
92
+ ### Rails support
93
+
94
+ Gruby supports ruby on rails integration.
95
+
96
+ To use in rails, Add dependency to Gemfile.
97
+
98
+ Then invoke install task.
99
+ ```
100
+ bin/rails glueby:contract:install
101
+ ```
102
+
103
+ Install task creates a file `glueby.rb` in `config/initializers` directory like this.
104
+ ```
105
+ require 'tapyrus'
106
+ # Edit configuration for connection to tapyrus core
107
+ config = {schema: 'http', host: '127.0.0.1', port: 12381, user: 'user', password: 'pass'}
108
+ Glueby::Contract::RPC.configure(config)
109
+ ```
110
+
111
+ If you use timestamp feature, use `glueby:contract:timestamp` generator.
112
+ ```
113
+ bin/rails g glueby:contract:timestamp
114
+ create db/migrate/20200613065511_create_timestamp.rb
115
+ bin/rails db:migrate
116
+ == 20200613065511 CreateTimestamp: migrating ==================================
117
+ -- create_table(:timestamps)
118
+ -> 0.0023s
119
+ == 20200613065511 CreateTimestamp: migrated (0.0024s) =========================
120
+ ```
121
+
122
+ Now, Glueby::Contract::AR::Timestamp model is available
123
+
124
+ ```ruby
125
+ irb(main):001:0> t = Glueby::AR::Contract::Timestamp.new(content:"\x01010101", prefix: "app")
126
+ (0.4ms) SELECT sqlite_version(*)
127
+ => #<Glueby::AR::Contract::Timestamp id: nil, txid: nil, vout: nil, status: "init", content_hash: "9ccc644b03a88358a754962903a659a2d338767ee61674dde5...", prefix: "app">
128
+ irb(main):002:0> t.save
129
+ (0.1ms) begin transaction
130
+ Glueby::AR::Contract::Timestamp Create (0.7ms) INSERT INTO "timestamps" ("status", "content_hash", "prefix") VALUES (?, ?, ?) [["status", 0], ["content_hash", "9ccc644b03a88358a754962903a659a2d338767ee61674dde5434702a6256e6d"], ["prefix", "app"]]
131
+ (2.3ms) commit transaction
132
+ => true
133
+ ```
134
+
135
+ After create timestamp model, run `glueby:contract:timestamp:create` task to broadcast the transaction to the Tapyrus Core Network and update status(init -> unconfirmed).
136
+
137
+ ```
138
+ bin/rails glueby:contract:timestamp:create
139
+ broadcasted (id=1, txid=8d602ca8ebdd50fa70b5ee6bc6351965b614d0a4843adacf9f43fedd7112fbf4)
140
+ ```
141
+
142
+ Run `glueby:contract:timestamp:confirm` task to confirm the transaction and update status(unconfirmed -> confirmded).
143
+ ```
144
+ bin/rails glueby:contract:timestamp:confirm
145
+ confirmed (id=1, txid=8d602ca8ebdd50fa70b5ee6bc6351965b614d0a4843adacf9f43fedd7112fbf4)
146
+ ```
147
+
148
+
149
+ ## Development
150
+
151
+ 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.
152
+
153
+ 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).
154
+
155
+ ## Contributing
156
+
157
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/glueby. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/[USERNAME]/tapyrus-contractrb/blob/master/CODE_OF_CONDUCT.md).
158
+
159
+
160
+ ## License
161
+
162
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
163
+
164
+ ## Code of Conduct
165
+
166
+ Everyone interacting in the Glueby project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/glueby/blob/master/CODE_OF_CONDUCT.md).
@@ -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
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "glueby"
5
+ require "tapyrus"
6
+
7
+ # You can add fixtures and/or initialization code here to make experimenting
8
+ # with your gem easier. You can also use a different console, if you like.
9
+
10
+ # (If you use this, don't forget to add pry to your Gemfile!)
11
+ # require "pry"
12
+ # Pry.start
13
+
14
+ require "irb"
15
+ IRB.start(__FILE__)
@@ -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
@@ -0,0 +1,32 @@
1
+ require_relative 'lib/glueby/version'
2
+
3
+ Gem::Specification.new do |spec|
4
+ spec.name = "glueby"
5
+ spec.version = Glueby::VERSION
6
+ spec.authors = ["azuchi"]
7
+ spec.email = ["azuchi@chaintope.com"]
8
+
9
+ spec.summary = %q{A Ruby library of smart contracts that can be used on Tapyrus.}
10
+ spec.description = %q{A Ruby library of smart contracts that can be used on Tapyrus.}
11
+ spec.homepage = "https://github.com/chaintope/glueby"
12
+ spec.license = "MIT"
13
+ spec.required_ruby_version = Gem::Requirement.new(">= 2.3.0")
14
+
15
+
16
+ spec.metadata["homepage_uri"] = spec.homepage
17
+ spec.metadata["source_code_uri"] = "https://github.com/chaintope/glueby"
18
+ spec.metadata["changelog_uri"] = "https://github.com/chaintope/glueby"
19
+
20
+ # Specify which files should be added to the gem when it is released.
21
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
22
+ spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
23
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
24
+ end
25
+ spec.bindir = "exe"
26
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
27
+ spec.require_paths = ["lib"]
28
+
29
+ spec.add_runtime_dependency 'tapyrus'
30
+ spec.add_development_dependency 'activerecord'
31
+ spec.add_development_dependency 'sqlite3'
32
+ end
@@ -0,0 +1,11 @@
1
+ module Glueby
2
+ module Contract
3
+ class InitializerGenerator < Rails::Generators::Base
4
+ source_root File.expand_path('templates', __dir__)
5
+
6
+ def create_initializer_file
7
+ template "initializer.rb.erb", "config/initializers/glueby.rb"
8
+ end
9
+ end
10
+ end
11
+ end
@@ -0,0 +1,4 @@
1
+ require 'tapyrus'
2
+ # Edit configuration for connection to tapyrus core
3
+ config = {schema: 'http', host: '127.0.0.1', port: 12381, user: 'user', password: 'pass'}
4
+ Glueby::Contract::RPC.configure(config)
@@ -0,0 +1,10 @@
1
+ class CreateTimestamp < ActiveRecord::Migration<%= migration_version %>
2
+ def change
3
+ create_table :timestamps<%= table_options %> do |t|
4
+ t.string :txid
5
+ t.integer :status
6
+ t.string :content_hash
7
+ t.string :prefix
8
+ end
9
+ end
10
+ end
@@ -0,0 +1,57 @@
1
+ module Glueby
2
+ module Contract
3
+ class TimestampGenerator < Rails::Generators::Base
4
+ include ::Rails::Generators::Migration
5
+
6
+ source_root File.expand_path('templates', __dir__)
7
+
8
+ def self.next_migration_number(dirname)
9
+ # ::ActiveRecord::Migration.next_migration_number(number)
10
+ # ::ActiveRecord::Generators::Base.next_migration_number(dirname)
11
+ next_migration_number = current_migration_number(dirname) + 1
12
+ ::ActiveRecord::Migration.next_migration_number(next_migration_number)
13
+ end
14
+
15
+ def create_migration_file
16
+ migration_dir = File.expand_path("db/migrate")
17
+
18
+ if self.class.migration_exists?(migration_dir, "create_timestamp")
19
+ ::Kernel.warn "Migration already exists: create_timestamp"
20
+ else
21
+ migration_template(
22
+ "timestamp_table.rb.erb",
23
+ "db/migrate/create_timestamp.rb",
24
+ migration_version: migration_version,
25
+ table_options: table_options,
26
+ )
27
+ end
28
+ end
29
+
30
+ MYSQL_ADAPTERS = [
31
+ "ActiveRecord::ConnectionAdapters::MysqlAdapter",
32
+ "ActiveRecord::ConnectionAdapters::Mysql2Adapter"
33
+ ].freeze
34
+
35
+ private
36
+
37
+ def migration_version
38
+ major = ::Rails::VERSION::MAJOR
39
+ if major >= 5
40
+ "[#{major}.#{::Rails::VERSION::MINOR}]"
41
+ end
42
+ end
43
+
44
+ def mysql?
45
+ MYSQL_ADAPTERS.include?(::ActiveRecord::Base.connection.class.name)
46
+ end
47
+
48
+ def table_options
49
+ if mysql?
50
+ ', { options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci" }'
51
+ else
52
+ ""
53
+ end
54
+ end
55
+ end
56
+ end
57
+ end
@@ -0,0 +1,5 @@
1
+ require "glueby/version"
2
+
3
+ module Glueby
4
+ autoload :Contract, 'glueby/contract'
5
+ end
@@ -0,0 +1,24 @@
1
+ module Glueby
2
+ module Contract
3
+ autoload :Errors, 'glueby/contract/errors'
4
+ autoload :FeeProvider, 'glueby/contract/fee_provider'
5
+ autoload :FixedFeeProvider, 'glueby/contract/fee_provider'
6
+ autoload :RPC, 'glueby/contract/rpc'
7
+ autoload :Timestamp, 'glueby/contract/timestamp'
8
+ autoload :TxBuilder, 'glueby/contract/tx_builder'
9
+ autoload :WalletFeature, 'glueby/contract/wallet_feature'
10
+ autoload :AR, 'glueby/contract/active_record'
11
+
12
+ begin
13
+ class Railtie < ::Rails::Railtie
14
+ rake_tasks do
15
+ load "tasks/glueby/contract.rake"
16
+ load "tasks/glueby/contract/timestamp.rake"
17
+ end
18
+ end
19
+ rescue
20
+ # Rake task is unavailable
21
+ puts "Rake task is unavailable"
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,9 @@
1
+ require 'active_record'
2
+
3
+ module Glueby
4
+ module Contract
5
+ module AR
6
+ autoload :Timestamp, 'glueby/contract/active_record/timestamp'
7
+ end
8
+ end
9
+ end
@@ -0,0 +1,17 @@
1
+ module Glueby
2
+ module Contract
3
+ module AR
4
+ class Timestamp < ::ActiveRecord::Base
5
+ include Glueby::Contract::Timestamp::Util
6
+ enum status: { init: 0, unconfirmed: 1, confirmed: 2 }
7
+
8
+ # @param [String] content Data to be hashed and stored in blockchain.
9
+ # @param [String] prefix prefix of op_return data
10
+ def initialize(content:, prefix: '')
11
+ @content_hash = Tapyrus.sha256(content).bth
12
+ super(content_hash: @content_hash, prefix: prefix, status: :init)
13
+ end
14
+ end
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,8 @@
1
+ module Glueby
2
+ module Contract
3
+ module Errors
4
+ class InsufficientFunds < StandardError; end
5
+ class TxAlreadyBroadcasted < StandardError; end
6
+ end
7
+ end
8
+ end
@@ -0,0 +1,21 @@
1
+ module Glueby
2
+ module Contract
3
+ module FeeProvider
4
+ # @return fee by tapyrus(not TPC).
5
+ def fee(_tx); end
6
+ end
7
+
8
+ class FixedFeeProvider
9
+ include FeeProvider
10
+
11
+ def initialize(fixed_fee: 10_000)
12
+ @fixed_fee = fixed_fee
13
+ end
14
+
15
+ # @return fee by tapyrus(not TPC).
16
+ def fee(_tx)
17
+ @fixed_fee
18
+ end
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,15 @@
1
+ module Glueby
2
+ module Contract
3
+ module RPC
4
+ module_function
5
+
6
+ def client
7
+ @rpc
8
+ end
9
+
10
+ def configure(config)
11
+ @rpc = Tapyrus::RPC::TapyrusCoreClient.new(config)
12
+ end
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,99 @@
1
+ module Glueby
2
+ module Contract
3
+ # Timestamp feature allows users to send transaction with op_return output which has sha256 hash of arbitary data.
4
+ # Timestamp transaction has
5
+ # * 1 or more inputs enough to afford transaction fee.
6
+ # * 1 output which has op_return, application specific prefix, and sha256 hash of data.
7
+ # * 1 output to send the change TPC back to the wallet.
8
+ #
9
+ # Storing timestamp transaction to the blockchain enables everyone to verify that the data existed at that time and a user signed it.
10
+ class Timestamp
11
+ include Glueby::Contract::TxBuilder
12
+
13
+ module Util
14
+ module_function
15
+
16
+ def create_tx(prefix, data_hash, fee_provider)
17
+ tx = Tapyrus::Tx.new
18
+ tx.outputs << Tapyrus::TxOut.new(value: 0, script_pubkey: create_script(prefix, data_hash))
19
+
20
+ results = list_unspent
21
+ fee = fee_provider.fee(tx)
22
+ sum, outputs = collect_outputs(results, fee)
23
+ fill_input(tx, outputs)
24
+
25
+ change_script = create_change_script
26
+ fill_change_output(tx, fee, change_script, sum)
27
+ tx
28
+ end
29
+
30
+ def create_payload(prefix, data_hash)
31
+ payload = +''
32
+ payload << prefix
33
+ payload << data_hash
34
+ payload
35
+ end
36
+
37
+ def create_script(prefix, data_hash)
38
+ script = Tapyrus::Script.new
39
+ script << Tapyrus::Script::OP_RETURN
40
+ script << create_payload(prefix, data_hash)
41
+ script
42
+ end
43
+
44
+ def create_change_script
45
+ address = Glueby::Contract::RPC.client.getnewaddress
46
+ decoded = Tapyrus.decode_base58_address(address)
47
+ Tapyrus::Script.to_p2pkh(decoded[0])
48
+ end
49
+
50
+ def sign_tx(tx)
51
+ # TODO: Implement SignatureProvider
52
+ response = Glueby::Contract::RPC.client.signrawtransactionwithwallet(tx.to_payload.bth)
53
+ Tapyrus::Tx.parse_from_payload(response['hex'].htb)
54
+ end
55
+
56
+ def list_unspent
57
+ # TODO: Implement UtxoProvider
58
+ Glueby::Contract::RPC.client.listunspent(0, 999_999)
59
+ end
60
+
61
+ def broadcast_tx(tx)
62
+ Glueby::Contract::RPC.client.sendrawtransaction(tx.to_payload.bth)
63
+ end
64
+
65
+ def get_transaction(tx)
66
+ Glueby::Contract::RPC.client.getrawtransaction(tx.txid, 1)
67
+ end
68
+ end
69
+ include Glueby::Contract::Timestamp::Util
70
+
71
+ attr_reader :tx, :txid
72
+
73
+ # @param [String] content Data to be hashed and stored in blockchain.
74
+ # @param [String] prefix prefix of op_return data
75
+ # @param [Glueby::Contract::FeeProvider] fee_provider
76
+ def initialize(
77
+ content:,
78
+ prefix: '',
79
+ fee_provider: Glueby::Contract::FixedFeeProvider.new
80
+ )
81
+ @content = content
82
+ @prefix = prefix
83
+ @fee_provider = fee_provider
84
+ end
85
+
86
+ # broadcast to Tapyrus Core
87
+ # @return [String] txid
88
+ # @raise [TxAlreadyBroadcasted] if tx has been broadcasted.
89
+ # @raise [InsufficientFunds] if result of listunspent is not enough to pay the specified amount
90
+ def save!
91
+ raise Glueby::Contract::Errors::TxAlreadyBroadcasted if @txid
92
+
93
+ @tx = create_tx(@prefix, Tapyrus.sha256(@content), @fee_provider)
94
+ @tx = sign_tx(@tx)
95
+ @txid = broadcast_tx(@tx)
96
+ end
97
+ end
98
+ end
99
+ end
@@ -0,0 +1,47 @@
1
+ module Glueby
2
+ module Contract
3
+ module TxBuilder
4
+ # collect outputs in results so that sum of them exceeds up to the specified amount.
5
+ # @param [Array] results of listunspent
6
+ # @param [Numeric] amount
7
+ # @return [(Numeric, Array)] sum value of outputs and outputs
8
+ # @raise [InsufficientFunds] if result of listunspent is not enough to pay the specified amount
9
+ def collect_outputs(results, amount)
10
+ results.inject([0, []]) do |sum, output|
11
+ new_sum = sum[0] + (output['amount'] * 100_000_000)
12
+ new_outputs = sum[1] << output
13
+ return [new_sum, new_outputs] if new_sum >= amount
14
+
15
+ [new_sum, new_outputs]
16
+ end
17
+ raise Glueby::Contract::Errors::InsufficientFunds
18
+ end
19
+
20
+ # Add inputs to tx
21
+ # @param [Tapyrus::Tx] tx
22
+ # @param [Array] outputs provided as result of listunspent and extracted by #collect_outputs methods
23
+ # @return [Tapyrus::Tx] tx which has enough amount in inputs.
24
+ def fill_input(tx, outputs)
25
+ outputs.each do |output|
26
+ out_point = Tapyrus::OutPoint.new(output['txid'].rhex, output['vout'])
27
+ tx.inputs << Tapyrus::TxIn.new(out_point: out_point)
28
+ end
29
+ tx
30
+ end
31
+
32
+ # Add output to tx, so that allow tx to return the change of the transaction.
33
+ # @param [Tapyrus::Tx] tx
34
+ # @param [Numeric] fee
35
+ # @param [Tapyrus::Script] script for change
36
+ # @param [Numeric] sum value of inputs
37
+ def fill_change_output(tx, fee, change_script, sum)
38
+ amount = fee + tx.outputs.map(&:value).sum
39
+ if amount.positive?
40
+ change = sum - amount
41
+ tx.outputs << Tapyrus::TxOut.new(value: change, script_pubkey: change_script)
42
+ end
43
+ tx
44
+ end
45
+ end
46
+ end
47
+ end
@@ -0,0 +1,3 @@
1
+ module Glueby
2
+ VERSION = "0.1.0"
3
+ end
@@ -0,0 +1,9 @@
1
+
2
+ namespace :glueby do
3
+ namespace :contract do
4
+ desc 'initialize glueby contract config'
5
+ task :install, [] => [:environment] do |_, _|
6
+ Rails::Generators.invoke("glueby:contract:initializer")
7
+ end
8
+ end
9
+ end
@@ -0,0 +1,62 @@
1
+ module Glueby
2
+ module Contract
3
+ module Task
4
+ module Timestamp
5
+ module_function
6
+ extend Glueby::Contract::TxBuilder
7
+ extend Glueby::Contract::Timestamp::Util
8
+
9
+ def create
10
+ timestamps = Glueby::Contract::AR::Timestamp.where(status: :init)
11
+ timestamps.each do |t|
12
+ begin
13
+ ::ActiveRecord::Base.transaction do
14
+ tx = create_tx(t.prefix, t.content_hash, Glueby::Contract::FixedFeeProvider.new)
15
+ signed_tx = sign_tx(tx)
16
+ t.update(txid: signed_tx.txid, status: :unconfirmed)
17
+
18
+ broadcast_tx(signed_tx)
19
+ puts "broadcasted (id=#{t.id}, txid=#{signed_tx.txid})"
20
+ end
21
+ rescue => e
22
+ puts "failed to broadcast (id=#{t.id}, reason=#{e.message})"
23
+ end
24
+ end
25
+ end
26
+
27
+ def confirm
28
+ timestamps = Glueby::Contract::AR::Timestamp.where(status: :unconfirmed)
29
+ timestamps.each do |t|
30
+ begin
31
+ ::ActiveRecord::Base.transaction do
32
+ tx = get_transaction(t)
33
+ if tx['confirmations'] && tx['confirmations'] > 0
34
+ t.update(status: :confirmed)
35
+ puts "confirmed (id=#{t.id}, txid=#{tx['txid']})"
36
+ end
37
+ end
38
+ rescue => e
39
+ puts "failed to confirm (id=#{t.id}, reason=#{e.message})"
40
+ end
41
+ end
42
+ end
43
+ end
44
+ end
45
+ end
46
+ end
47
+
48
+ namespace :glueby do
49
+ namespace :contract do
50
+ namespace :timestamp do
51
+ desc 'create and broadcast glueby timestamp tx'
52
+ task :create, [] => [:environment] do |_, _|
53
+ Glueby::Contract::Task::Timestamp.create
54
+ end
55
+
56
+ desc 'confirm glueby timestamp tx'
57
+ task :confirm, [] => [:environment] do |_, _|
58
+ Glueby::Contract::Task::Timestamp.confirm
59
+ end
60
+ end
61
+ end
62
+ end
metadata ADDED
@@ -0,0 +1,117 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: glueby
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - azuchi
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2020-07-03 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: tapyrus
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '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'
27
+ - !ruby/object:Gem::Dependency
28
+ name: activerecord
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: sqlite3
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ description: A Ruby library of smart contracts that can be used on Tapyrus.
56
+ email:
57
+ - azuchi@chaintope.com
58
+ executables: []
59
+ extensions: []
60
+ extra_rdoc_files: []
61
+ files:
62
+ - ".gitignore"
63
+ - ".rspec"
64
+ - ".ruby-gemset"
65
+ - ".ruby-version"
66
+ - ".travis.yml"
67
+ - CODE_OF_CONDUCT.md
68
+ - Gemfile
69
+ - LICENSE.txt
70
+ - README.md
71
+ - Rakefile
72
+ - bin/console
73
+ - bin/setup
74
+ - glueby.gemspec
75
+ - lib/generators/glueby/initializer_generator.rb
76
+ - lib/generators/glueby/templates/initializer.rb.erb
77
+ - lib/generators/glueby/templates/timestamp_table.rb.erb
78
+ - lib/generators/glueby/timestamp_generator.rb
79
+ - lib/glueby.rb
80
+ - lib/glueby/contract.rb
81
+ - lib/glueby/contract/active_record.rb
82
+ - lib/glueby/contract/active_record/timestamp.rb
83
+ - lib/glueby/contract/errors.rb
84
+ - lib/glueby/contract/fee_provider.rb
85
+ - lib/glueby/contract/rpc.rb
86
+ - lib/glueby/contract/timestamp.rb
87
+ - lib/glueby/contract/tx_builder.rb
88
+ - lib/glueby/version.rb
89
+ - lib/tasks/glueby/contract.rake
90
+ - lib/tasks/glueby/contract/timestamp.rake
91
+ homepage: https://github.com/chaintope/glueby
92
+ licenses:
93
+ - MIT
94
+ metadata:
95
+ homepage_uri: https://github.com/chaintope/glueby
96
+ source_code_uri: https://github.com/chaintope/glueby
97
+ changelog_uri: https://github.com/chaintope/glueby
98
+ post_install_message:
99
+ rdoc_options: []
100
+ require_paths:
101
+ - lib
102
+ required_ruby_version: !ruby/object:Gem::Requirement
103
+ requirements:
104
+ - - ">="
105
+ - !ruby/object:Gem::Version
106
+ version: 2.3.0
107
+ required_rubygems_version: !ruby/object:Gem::Requirement
108
+ requirements:
109
+ - - ">="
110
+ - !ruby/object:Gem::Version
111
+ version: '0'
112
+ requirements: []
113
+ rubygems_version: 3.0.3
114
+ signing_key:
115
+ specification_version: 4
116
+ summary: A Ruby library of smart contracts that can be used on Tapyrus.
117
+ test_files: []