调整了blockchain api

This commit is contained in:
zhangxunhui 2023-02-04 11:06:04 +08:00
parent b1ef05e0be
commit 06a6794245
15 changed files with 188 additions and 263 deletions

View File

@ -895,66 +895,6 @@ class ApplicationController < ActionController::Base
HotSearchKeyword.add(keyword) HotSearchKeyword.add(keyword)
end end
# author: zxh
# blockchain存证api
#def invoke_blockchain_api(uri, params)
# begin
# uri = URI.parse(URI.encode(uri.strip))
# res = Net::HTTP.start(uri.host, uri.port) do |http|
# req = Net::HTTP::Post.new(uri)
# req['Content-Type'] = 'application/json'
# req.body = params
# http.request(req)
# end
# if res.code.to_i != 200
# puts '区块链接口请求失败.'
# return false
# else
# res_body = JSON.parse(res.body)
# if res_body.has_key?("data") && JSON.parse(res_body["data"]).has_key?("status") && JSON.parse(res_body["data"])['status'] == "Success"
# else
# puts '区块链接口请求出错.'
# return false
# end
# end
#
# return true
# rescue Exception => e
# puts '区块链接口请求失败.'
# return false
# end
#end
def invoke_blockchain_api(uri, params)
begin
uri = URI.parse(URI.encode(uri.strip))
res = Net::HTTP.start(uri.host, uri.port) do |http|
req = Net::HTTP::Post.new(uri)
req['Content-Type'] = 'application/json'
req.body = params
http.request(req)
end
if res.code.to_i != 200
puts '区块链接口请求失败.'
return false
else
res_body = JSON.parse(res.body)
if res_body.has_key?("status") && res_body["status"] == 0
else
puts '区块链接口请求出错.'
return false
end
end
return true
rescue Exception => e
puts '区块链接口请求失败.'
return false
end
end
# author: zxh # author: zxh
# blockchain相关项目活动调用函数 # blockchain相关项目活动调用函数
# return true: 表示上链操作成功; return false: 表示上链操作失败 # return true: 表示上链操作成功; return false: 表示上链操作失败
@ -987,7 +927,7 @@ class ApplicationController < ActionController::Base
updated_at = model['updated_on'] updated_at = model['updated_on']
# 调用区块链接口 # 调用区块链接口
param = { params = {
"request-type": "upload issue info", "request-type": "upload issue info",
"issue_id": "gitlink-" + id.to_s, "issue_id": "gitlink-" + id.to_s,
"repo_id": "gitlink-" + project_id.to_s, "repo_id": "gitlink-" + project_id.to_s,
@ -1001,8 +941,12 @@ class ApplicationController < ActionController::Base
"created_at": created_at, "created_at": created_at,
"updated_at": updated_at "updated_at": updated_at
}.to_json }.to_json
success_blockchain = invoke_blockchain_api(Blockchain.blockchain_config[:api_url], param) resp_body = Blockchain::InvokeBlockchainApi.call(params)
return success_blockchain if resp_body['status'] == 10
raise Error, resp_body['message']
elsif resp_body['status'] != 0
raise Error, "区块链接口请求失败."
end
elsif activity_type == "issue_comment_create" elsif activity_type == "issue_comment_create"
issue_comment_id = model['id'] issue_comment_id = model['id']
@ -1016,7 +960,7 @@ class ApplicationController < ActionController::Base
if project['use_blockchain'] == 0 || project['use_blockchain'] == false if project['use_blockchain'] == 0 || project['use_blockchain'] == false
# 无需执行上链操作 # 无需执行上链操作
return true return
end end
identifier = project['identifier'] identifier = project['identifier']
@ -1034,7 +978,7 @@ class ApplicationController < ActionController::Base
created_at = model['created_on'] created_at = model['created_on']
if issue_classify == "issue" if issue_classify == "issue"
param = { params = {
"request-type": "upload issue comment info", "request-type": "upload issue comment info",
"issue_comment_id": "gitlink-" + issue_comment_id.to_s, "issue_comment_id": "gitlink-" + issue_comment_id.to_s,
"issue_comment_number": 0, # 暂时不需要 "issue_comment_number": 0, # 暂时不需要
@ -1050,7 +994,7 @@ class ApplicationController < ActionController::Base
"created_at": created_at, "created_at": created_at,
}.to_json }.to_json
elsif issue_classify == "pull_request" elsif issue_classify == "pull_request"
param = { params = {
"request-type": "upload pull request comment info", "request-type": "upload pull request comment info",
"pull_request_comment_id": "gitlink-" + issue_comment_id.to_s, "pull_request_comment_id": "gitlink-" + issue_comment_id.to_s,
"pull_request_comment_number": 0, # 不考虑该字段 "pull_request_comment_number": 0, # 不考虑该字段
@ -1068,15 +1012,19 @@ class ApplicationController < ActionController::Base
end end
# 调用区块链接口 # 调用区块链接口
success_blockchain = invoke_blockchain_api(Blockchain.blockchain_config[:api_url], param) resp_body = Blockchain::InvokeBlockchainApi.call(params)
return success_blockchain if resp_body['status'] == 10
raise Error, resp_body['message']
elsif resp_body['status'] != 0
raise Error, "区块链接口请求失败."
end
elsif activity_type == "pull_request_create" elsif activity_type == "pull_request_create"
# 调用区块链接口 # 调用区块链接口
project_id = model['project_id'] project_id = model['project_id']
project = Project.find(project_id) project = Project.find(project_id)
if project['use_blockchain'] == 0 || project['use_blockchain'] == false if project['use_blockchain'] == 0 || project['use_blockchain'] == false
# 无需执行上链操作 # 无需执行上链操作
return true return
end end
pull_request_id = model['id'] pull_request_id = model['id']
@ -1106,13 +1054,13 @@ class ApplicationController < ActionController::Base
# 查询pull request对应的commit信息 # 查询pull request对应的commit信息
commits = Gitea::PullRequest::CommitsService.call(ownername, identifier, model['gitea_number']) commits = Gitea::PullRequest::CommitsService.call(ownername, identifier, model['gitea_number'])
if commits.nil? if commits.nil?
return false # 获取pr中变更的commit信息失败 raise Error, "区块链接口请求失败" # 获取pr中变更的commit信息失败
end end
commit_shas = [] commit_shas = []
commits.each do |c| commits.each do |c|
commit_shas << c["Sha"] commit_shas << c["Sha"]
end end
param = { params = {
"request-type": "upload pull request info", "request-type": "upload pull request info",
"pull_request_id": "gitlink-" + pull_request_id.to_s, "pull_request_id": "gitlink-" + pull_request_id.to_s,
"pull_request_number": 0, # trustie没有该字段 "pull_request_number": 0, # trustie没有该字段
@ -1131,16 +1079,19 @@ class ApplicationController < ActionController::Base
"created_at": created_at, "created_at": created_at,
"updated_at": updated_at "updated_at": updated_at
}.to_json }.to_json
success_blockchain = invoke_blockchain_api(Blockchain.blockchain_config[:api_url], param) resp_body = Blockchain::InvokeBlockchainApi.call(params)
return success_blockchain if resp_body['status'] == 9
raise Error, resp_body['message']
elsif resp_body['status'] != 0
raise Error, "区块链接口请求失败."
end
elsif activity_type == "pull_request_merge" elsif activity_type == "pull_request_merge"
# 调用区块链接口 # 调用区块链接口
project_id = model['project_id'] project_id = model['project_id']
project = Project.find(project_id) project = Project.find(project_id)
if project['use_blockchain'] == 0 || project['use_blockchain'] == false if project['use_blockchain'] == 0 || project['use_blockchain'] == false
# 无需执行上链操作 # 无需执行上链操作
return true return
end end
pull_request_id = model['id'] pull_request_id = model['id']
@ -1157,7 +1108,7 @@ class ApplicationController < ActionController::Base
# 查询pull request对应的commit信息 # 查询pull request对应的commit信息
commits = Gitea::PullRequest::CommitsService.call(ownername, identifier, model['gitea_number']) commits = Gitea::PullRequest::CommitsService.call(ownername, identifier, model['gitea_number'])
if commits.nil? if commits.nil?
return false # 获取pr中变更的commit信息失败 raise Error, "区块链接口请求失败" # 获取pr中变更的commit信息失败
end end
commit_shas = [] commit_shas = []
commits.each do |c| commits.each do |c|
@ -1165,7 +1116,7 @@ class ApplicationController < ActionController::Base
end end
# 将pull request相关信息写入链上 # 将pull request相关信息写入链上
param = { params = {
"request-type": "upload pull request info", "request-type": "upload pull request info",
"pull_request_id": "gitlink-" + pull_request_id.to_s, "pull_request_id": "gitlink-" + pull_request_id.to_s,
"pull_request_number": 0, # trustie没有该字段 "pull_request_number": 0, # trustie没有该字段
@ -1184,14 +1135,19 @@ class ApplicationController < ActionController::Base
"created_at": created_at, "created_at": created_at,
"updated_at": updated_at "updated_at": updated_at
}.to_json }.to_json
success_blockchain = invoke_blockchain_api(Blockchain.blockchain_config[:api_url], param) resp_body = Blockchain::InvokeBlockchainApi.call(params)
if resp_body['status'] == 9
raise Error, resp_body['message']
elsif resp_body['status'] != 0
raise Error, "区块链接口请求失败."
end
# 将commit相关信息写入链上 # 将commit相关信息写入链上
commit_shas.each do |commit_sha| commit_shas.each do |commit_sha|
commit_diff = Gitea::Commit::DiffService.call(ownername, identifier, commit_sha, owner['gitea_token']) commit_diff = Gitea::Commit::DiffService.call(ownername, identifier, commit_sha, owner['gitea_token'])
commit = Gitea::Commit::InfoService.call(ownername, identifier, commit_sha, owner['gitea_token']) commit = Gitea::Commit::InfoService.call(ownername, identifier, commit_sha, owner['gitea_token'])
param = { params = {
"request-type": "upload commit info", "request-type": "upload commit info",
"commit_hash": commit_sha, "commit_hash": commit_sha,
"repo_id": "gitlink-" + project_id.to_s, "repo_id": "gitlink-" + project_id.to_s,
@ -1204,10 +1160,13 @@ class ApplicationController < ActionController::Base
"content": commit['commit']['message'], "content": commit['commit']['message'],
"commit_diff": commit_diff['Files'].to_s "commit_diff": commit_diff['Files'].to_s
}.to_json }.to_json
success_blockchain_commit = invoke_blockchain_api(Blockchain.blockchain_config[:api_url], param) resp_body = Blockchain::InvokeBlockchainApi.call(params)
success_blockchain = success_blockchain & success_blockchain_commit if resp_body['status'] == 7
raise Error, resp_body['message']
elsif resp_body['status'] != 0
raise Error, "区块链接口请求失败."
end
end end
return success_blockchain
elsif activity_type == "pull_request_refuse" elsif activity_type == "pull_request_refuse"
@ -1228,7 +1187,7 @@ class ApplicationController < ActionController::Base
action = 'refused' action = 'refused'
# 将pull request相关信息写入链上 # 将pull request相关信息写入链上
param = { params = {
"request-type": "upload pull request info", "request-type": "upload pull request info",
"pull_request_id": "gitlink-" + pull_request_id.to_s, "pull_request_id": "gitlink-" + pull_request_id.to_s,
"pull_request_number": 0, # trustie没有该字段 "pull_request_number": 0, # trustie没有该字段
@ -1247,8 +1206,12 @@ class ApplicationController < ActionController::Base
"created_at": created_at, "created_at": created_at,
"updated_at": updated_at "updated_at": updated_at
}.to_json }.to_json
success_blockchain = invoke_blockchain_api(Blockchain.blockchain_config[:api_url], param) resp_body = Blockchain::InvokeBlockchainApi.call(params)
return success_blockchain if resp_body['status'] == 9
raise Error, resp_body['message']
elsif resp_body['status'] != 0
raise Error, "区块链接口请求失败."
end
end end
end end
def find_atme_receivers def find_atme_receivers

View File

@ -160,22 +160,14 @@ class IssuesController < ApplicationController
# author: zxh # author: zxh
# 扣除发起人的token # 扣除发起人的token
blockchain_result = Blockchain::CreateIssue.call(user_id: @issue.author_id, project_id: @issue.project_id, token_num: @issue.blockchain_token_num) if @issue.blockchain_token_num > 0
if blockchain_result = false Blockchain::CreateIssue.call(user_id: @issue.author_id, project_id: @issue.project_id, token_num: @issue.blockchain_token_num)
normal_status(-1, "创建失败")
raise ActiveRecord::Rollback
else
end
#render json: {status: 0, message: "创建成功", id: @issue.id}
# 调用上链API存证
success_blockchain = push_activity_2_blockchain("issue_create", @issue)
if success_blockchain == false
normal_status(-1, "创建失败")
raise ActiveRecord::Rollback
else
render json: {status: 0, message: "创建成功", id: @issue.id}
end end
# 调用上链API存证
push_activity_2_blockchain("issue_create", @issue)
render json: {status: 0, message: "创建成功", id: @issue.id}
else else
normal_status(-1, "创建失败") normal_status(-1, "创建失败")
end end

View File

@ -51,14 +51,9 @@ class JournalsController < ApplicationController
# author: zxh # author: zxh
# 调用上链API # 调用上链API
success_blockchain = push_activity_2_blockchain("issue_comment_create", journal) push_activity_2_blockchain("issue_comment_create", journal)
if success_blockchain == false
normal_status(-1, "评论失败")
raise ActiveRecord::Rollback
end
render :json => { status: 0, message: "评论成功", id: journal.id} render :json => { status: 0, message: "评论成功", id: journal.id}
# normal_status(0, "评论成功")
else else
normal_status(-1, "评论失败") normal_status(-1, "评论失败")
raise ActiveRecord::Rollback raise ActiveRecord::Rollback

View File

@ -78,11 +78,8 @@ class PullRequestsController < ApplicationController
# author: zxh # author: zxh
# 调用上链API # 调用上链API
success_blockchain = push_activity_2_blockchain("pull_request_create", @pull_request) push_activity_2_blockchain("pull_request_create", @pull_request)
if success_blockchain == false
render_error("create pull request error: cannot save to blockchain")
raise ActiveRecord::Rollback
end
else else
render_error("create pull request error: #{@gitea_pull_request[:status]}") render_error("create pull request error: #{@gitea_pull_request[:status]}")
raise ActiveRecord::Rollback raise ActiveRecord::Rollback
@ -166,20 +163,16 @@ class PullRequestsController < ApplicationController
colsed = PullRequests::CloseService.call(@owner, @repository, @pull_request, current_user) colsed = PullRequests::CloseService.call(@owner, @repository, @pull_request, current_user)
# author: zxh # author: zxh
# 调用上链API # 调用上链API
success_blockchain = push_activity_2_blockchain("pull_request_refuse", @pull_request) push_activity_2_blockchain("pull_request_refuse", @pull_request)
if success_blockchain == false
normal_status(-1, "拒绝失败") if colsed === true
raise ActiveRecord::Rollback @pull_request.project_trends.create!(user: current_user, project: @project,action_type: ProjectTrend::CLOSE)
# 合并请求下issue处理为关闭
@issue&.update_attributes!({status_id:5})
SendTemplateMessageJob.perform_later('PullRequestClosed', current_user.id, @pull_request.id) if Site.has_notice_menu?
normal_status(1, "已拒绝")
else else
if colsed === true normal_status(-1, '合并失败')
@pull_request.project_trends.create!(user: current_user, project: @project,action_type: ProjectTrend::CLOSE)
# 合并请求下issue处理为关闭
@issue&.update_attributes!({status_id:5})
SendTemplateMessageJob.perform_later('PullRequestClosed', current_user.id, @pull_request.id) if Site.has_notice_menu?
normal_status(1, "已拒绝")
else
normal_status(-1, '合并失败')
end
end end
rescue => e rescue => e
normal_status(-1, e.message) normal_status(-1, e.message)
@ -224,13 +217,7 @@ class PullRequestsController < ApplicationController
# author: zxh # author: zxh
# 调用上链API # 调用上链API
success_blockchain = push_activity_2_blockchain("pull_request_merge", @pull_request) push_activity_2_blockchain("pull_request_merge", @pull_request)
if success_blockchain == false
normal_status(-1, "合并失败")
raise ActiveRecord::Rollback
else
end
# 查看是否fix了相关issue如果fix就转账 # 查看是否fix了相关issue如果fix就转账
if params["fix_issue_id"].nil? || params["fix_issue_id"] == "" if params["fix_issue_id"].nil? || params["fix_issue_id"] == ""
@ -248,20 +235,17 @@ class PullRequestsController < ApplicationController
normal_status(-1, "关联issue失败") normal_status(-1, "关联issue失败")
raise ActiveRecord::Rollback raise ActiveRecord::Rollback
else else
project = Project.find_by(user_id: owner.id, name: params["project_id"]) project = Project.find_by(user_id: owner.id, identifier: params["project_id"])
if project.nil? if project.nil?
normal_status(-1, "关联issue失败") normal_status(-1, "关联issue失败")
raise ActiveRecord::Rollback raise ActiveRecord::Rollback
else else
author_id = pr.user_id author_id = pr.user_id
result = Blockchain::FixIssue.call({user_id: author_id.to_s, project_id: project.id.to_s, token_num: token_num}) if token_num > 0
if result == false Blockchain::FixIssue.call({user_id: author_id.to_s, project_id: project.id.to_s, token_num: token_num})
normal_status(-1, "关联issue失败")
raise ActiveRecord::Rollback
else
# update issue to state 5
issue.update(status_id: 5)
end end
# update issue to state 5
issue.update(status_id: 5)
end end
end end
end end

View File

@ -92,7 +92,7 @@ class UsersController < ApplicationController
end end
if @project['use_blockchain'] == true or @project['use_blockchain'] == 1 if @project['use_blockchain'] == true or @project['use_blockchain'] == 1
balance_user = Blockchain::BalanceQueryOneProject.call({"user_id": user_id, "project_id": project_id})[:balance] balance_user = Blockchain::BalanceQueryOneProject.call({"user_id": user_id, "project_id": project_id})
balance_all = Blockchain::RepoBasicInfo.call({"project_id": project_id})["cur_supply"] balance_all = Blockchain::RepoBasicInfo.call({"project_id": project_id})["cur_supply"]
scores = { scores = {
"final" => cal_perc(balance_user, balance_all), "final" => cal_perc(balance_user, balance_all),
@ -440,12 +440,10 @@ class UsersController < ApplicationController
normal_status(-1, "创建者无法找到") normal_status(-1, "创建者无法找到")
else else
p = Project.find_by(user_id: owner.id, identifier: params['project_identifier']) p = Project.find_by(user_id: owner.id, identifier: params['project_identifier'])
results = Blockchain::BalanceQueryOneProject.call({"user_id": params['user_id'].to_i, "project_id": p.id.to_i}) balance = Blockchain::BalanceQueryOneProject.call({"user_id": params['user_id'].to_i, "project_id": p.id.to_i})
render json: { status: results[:status], balance: results[:balance]} render json: { status: 0, balance: balance}
end end
else else
puts "~!@~!@" + params['user_id'].to_s
puts current_user.id.to_s
normal_status(-1, "缺少权限") normal_status(-1, "缺少权限")
end end
@ -455,16 +453,15 @@ class UsersController < ApplicationController
def blockchain_transfer def blockchain_transfer
#is_current_admin_user = User.current.logged? && (current_user&.admin? || current_user.id == params['payer_id'].to_i) #is_current_admin_user = User.current.logged? && (current_user&.admin? || current_user.id == params['payer_id'].to_i)
is_current_admin_user = true is_current_admin_user = true
if is_current_admin_user if is_current_admin_user
results = Blockchain::TransferService.call(params) Blockchain::TransferService.call(params)
if results == true render json: {status: 2} # 重新查询余额
render json: { status: 2 } # 重新查询余额
else
normal_status(-1, "转账失败")
end
else else
normal_status(-1, "缺少权限") normal_status(-1, "缺少权限")
end end
rescue Exception => e
normal_status(-1, e.to_s)
end end
# exchange money # exchange money
@ -640,7 +637,12 @@ class UsersController < ApplicationController
def blockchain_get_issue_token_num def blockchain_get_issue_token_num
issue_id = params["issue_id"]['orderId'].to_i issue_id = params["issue_id"]['orderId'].to_i
issue = Issue.find_by(id: issue_id) issue = Issue.find_by(id: issue_id)
render json: {"blockchain_token_num": issue.blockchain_token_num} project = Project.find(issue.project_id)
if project[:use_blockchain]
render json: {"blockchain_token_num": issue.blockchain_token_num}
else
render json: {"blockchain_token_num": -1} # 未使用blockchain
end
end end

View File

@ -21,7 +21,8 @@ module TagChosenHelper
"issue_tag": render_issue_tags(project), "issue_tag": render_issue_tags(project),
"issue_type": render_issue_species, "issue_type": render_issue_species,
"all_issues": all_issues, "all_issues": all_issues,
"branches": render_branches(project) "branches": render_branches(project),
"use_blockchain": project['use_blockchain']
} }
end end

View File

@ -42,7 +42,7 @@ module Watchable
end end
if @project['use_blockchain'] == true or @project['use_blockchain'] == 1 if @project['use_blockchain'] == true or @project['use_blockchain'] == 1
balance_user = Blockchain::BalanceQueryOneProject.call({"user_id": @user.id, "project_id": @project.id})[:balance] balance_user = Blockchain::BalanceQueryOneProject.call({"user_id": @user.id, "project_id": @project.id})
balance_all = Blockchain::RepoBasicInfo.call({"project_id": @project.id})["cur_supply"] balance_all = Blockchain::RepoBasicInfo.call({"project_id": @project.id})["cur_supply"]
score = cal_perc(balance_user, balance_all) score = cal_perc(balance_user, balance_all)
else else

View File

@ -7,70 +7,52 @@ class ApplicationQuery
params[key].to_s.strip.presence params[key].to_s.strip.presence
end end
# author: zxh
# add blockchain related functions in application_query
def invoke_blockchain_api(uri, params)
begin
uri = URI.parse(URI.encode(uri.strip))
res = Net::HTTP.start(uri.host, uri.port) do |http|
req = Net::HTTP::Post.new(uri)
req['Content-Type'] = 'application/json'
req.body = params
http.request(req)
end
if res.code.to_i != 200
puts '区块链接口请求失败.'
return false
else
res_body = JSON.parse(res.body)
if res_body.has_key?("status") && res_body["status"] == 0
else
puts '区块链接口请求出错.'
return false
end
end
return res_body
rescue Exception => e
puts '区块链接口请求失败.'
return false
end
end
# find all the repos that a user has tokens # find all the repos that a user has tokens
def find_repo_with_token(user_id) def find_repo_with_token(user_id)
param = { params = {
"request-type": "query user balance of all repos", "request-type": "query user balance of all repos",
"username": user_id.to_s "username": user_id.to_s
}.to_json }.to_json
resp_body = invoke_blockchain_api(Blockchain.blockchain_config[:api_url], param) resp_body = Blockchain::InvokeBlockchainApi.call(params)
token_list = resp_body['UserBalanceList'].nil? ? [] : resp_body['UserBalanceList'] if resp_body['status'] != 0
return token_list raise "区块链接口请求失败."
else
token_list = resp_body['UserBalanceList'].nil? ? [] : resp_body['UserBalanceList']
return token_list
end
end end
# find one repo that a user has tokens # find one repo that a user has tokens
def find_one_balance(user_id, project_id) def find_one_balance(user_id, project_id)
param = { # return 3 statuses: UnknownErr/ResUserNotExisted/Success
params = {
"request-type": "query user balance of single repo", "request-type": "query user balance of single repo",
"username": user_id.to_s, "username": user_id.to_s,
"token_name": project_id.to_s "token_name": project_id.to_s
}.to_json }.to_json
resp_body = invoke_blockchain_api(Blockchain.blockchain_config[:api_url], param) resp_body = Blockchain::InvokeBlockchainApi.call(params)
return resp_body if resp_body['status'] == 0
return resp_body['balance']
elsif resp_body['status'] == 100
return 0 # 找不到用户返回0
else
raise "区块链接口请求失败."
end
end end
# query the basic info of a repository # query the basic info of a repository
def find_blockchain_repo_info(project_id) def find_blockchain_repo_info(project_id)
param = { params = {
"request-type": "query repo basic info", "request-type": "query repo basic info",
"token_name": project_id.to_s "token_name": project_id.to_s
}.to_json }.to_json
resp_body = invoke_blockchain_api(Blockchain.blockchain_config[:api_url], param) resp_body = Blockchain::InvokeBlockchainApi.call(params)
return resp_body if resp_body['status'] == 0
return resp_body
else
raise "区块链接口请求失败."
end
end end
end end

View File

@ -7,12 +7,6 @@ class Blockchain::BalanceQueryOneProject < ApplicationQuery
end end
def call def call
balance = find_one_balance(params[:user_id].to_s, params[:project_id].to_s) find_one_balance(params[:user_id].to_s, params[:project_id].to_s)
if balance == false
return false
else
results = {"status": balance['status'], "balance": balance['balance']}
results
end
end end
end end

View File

@ -8,10 +8,6 @@ class Blockchain::RepoBasicInfo < ApplicationQuery
def call def call
info = find_blockchain_repo_info(params[:project_id].to_s) info = find_blockchain_repo_info(params[:project_id].to_s)
if info == false return info
return false
else
return info
end
end end
end end

View File

@ -19,39 +19,6 @@ class ApplicationService
ActiveModel::Type::Boolean.new.cast str ActiveModel::Type::Boolean.new.cast str
end end
# author: zxh
# blockchain创建项目相关api
def invoke_blockchain_api(uri, params)
begin
uri = URI.parse(URI.encode(uri.strip))
res = Net::HTTP.start(uri.host, uri.port) do |http|
req = Net::HTTP::Post.new(uri)
req['Content-Type'] = 'application/json'
req.body = params
http.request(req)
end
if res.code.to_i != 200
puts '区块链接口请求失败.'
return false
else
res_body = JSON.parse(res.body)
if res_body.has_key?("status") && res_body["status"] == 0
else
puts '区块链接口请求出错.'
return false
end
end
return true
rescue Exception => e
puts '区块链接口请求失败.'
return false
end
end
# params: params from index.js page # params: params from index.js page
def create_repo_on_blockchain(params, project) def create_repo_on_blockchain(params, project)
username = params['user_id'].to_s username = params['user_id'].to_s
@ -59,54 +26,72 @@ class ApplicationService
total_supply = params['blockchain_token_all'].to_i total_supply = params['blockchain_token_all'].to_i
token_balance = [[username, (total_supply * params['blockchain_init_token'].to_i / 100).to_i]] token_balance = [[username, (total_supply * params['blockchain_init_token'].to_i / 100).to_i]]
param = { params = {
"request-type": "create repo", "request-type": "create repo",
"username": username, "username": username,
"token_name": token_name, "token_name": token_name,
"total_supply": total_supply, "total_supply": total_supply,
"token_balance": token_balance "token_balance": token_balance
}.to_json }.to_json
invoke_blockchain_api(Blockchain.blockchain_config[:api_url], param) resp_body = Blockchain::InvokeBlockchainApi.call(params)
if resp_body['status'] != 0
raise "区块链接口请求失败."
end
end end
def transfer_balance_on_blockchain(payer, payee, token_name, amount) def transfer_balance_on_blockchain(payer, payee, token_name, amount)
param = { params = {
"request-type": "transfer amount", "request-type": "transfer amount",
"payer": payer, "payer": payer,
"payee": payee, "payee": payee,
"token_name": token_name, "token_name": token_name,
"amount": amount "amount": amount
}.to_json }.to_json
results = invoke_blockchain_api(Blockchain.blockchain_config[:api_url], param) resp_body = Blockchain::InvokeBlockchainApi.call(params)
return results if resp_body['status'] == 5 or resp_body['status'] == 106 or resp_body['status'] == 105
raise resp_body['message']
elsif resp_body['status'] != 0
raise "区块链接口请求失败."
else
end
end end
def lock_balance_on_blockchain(username, tokenname, amount) def lock_balance_on_blockchain(username, tokenname, amount)
param = { params = {
"request-type": "lock user balance", "request-type": "lock user balance",
"username": username, "username": username,
"token_name": tokenname, "token_name": tokenname,
"amount": amount "amount": amount
}.to_json }.to_json
results = invoke_blockchain_api(Blockchain.blockchain_config[:api_url], param) resp_body = Blockchain::InvokeBlockchainApi.call(params)
return results if resp_body['status'] == 5 or resp_body['status'] == 106 or resp_body['status'] == 103
raise resp_body['message']
elsif resp_body['status'] != 0
raise "区块链接口请求失败."
else
end
end end
def unlock_balance_on_blockchain(username, tokenname, amount) def unlock_balance_on_blockchain(username, tokenname, amount)
param = { params = {
"request-type": "unlock user balance", "request-type": "unlock user balance",
"username": username, "username": username,
"token_name": tokenname, "token_name": tokenname,
"amount": amount "amount": amount
}.to_json }.to_json
results = invoke_blockchain_api(Blockchain.blockchain_config[:api_url], param) resp_body = Blockchain::InvokeBlockchainApi.call(params)
return results if resp_body['status'] == 5 or resp_body['status'] == 106 or resp_body['status'] == 104
raise resp_body['message']
elsif resp_body['status'] != 0
raise "区块链接口请求失败."
else
end
end end
def phone_mail_type value def phone_mail_type value
value =~ /^1\d{10}$/ ? 1 : 0 value =~ /^1\d{10}$/ ? 1 : 0

View File

@ -13,8 +13,7 @@ class Blockchain::CreateIssue < ApplicationService
amount = @params[:token_num].to_i amount = @params[:token_num].to_i
# 调用token锁仓函数 # 调用token锁仓函数
results = lock_balance_on_blockchain(username, token_name, amount) lock_balance_on_blockchain(username, token_name, amount)
return results
end end
rescue => e rescue => e
puts "转账失败: #{e.message}" puts "转账失败: #{e.message}"

View File

@ -13,8 +13,7 @@ class Blockchain::FixIssue < ApplicationService
amount = @params[:token_num].to_i amount = @params[:token_num].to_i
# 调用token锁仓函数 # 调用token锁仓函数
results = unlock_balance_on_blockchain(username, token_name, amount) unlock_balance_on_blockchain(username, token_name, amount)
return results
end end
rescue => e rescue => e
puts "关联issue失败: #{e.message}" puts "关联issue失败: #{e.message}"

View File

@ -0,0 +1,34 @@
class Blockchain::InvokeBlockchainApi < ApplicationService
# 调用blockchain
attr_reader :params
def initialize(params)
@params = params
end
def call
begin
uri = Blockchain.blockchain_config[:api_url]
uri = URI.parse(URI.encode(uri.strip))
res = Net::HTTP.start(uri.host, uri.port) do |http|
req = Net::HTTP::Post.new(uri)
req['Content-Type'] = 'application/json'
req.body = @params
http.request(req)
end
if res.code.to_i != 200
raise "区块链接口请求失败."
else
res_body = JSON.parse(res.body)
if res_body.has_key?("status")
else
raise "区块链接口请求失败."
end
end
return res_body
rescue Exception => e
raise "区块链接口请求失败."
end
end
end

View File

@ -8,25 +8,23 @@ class Blockchain::TransferService < ApplicationService
def call def call
ActiveRecord::Base.transaction do ActiveRecord::Base.transaction do
transfer_amount = params['transfer_amount']
if (Float(transfer_amount) rescue false) == false or transfer_amount.to_i < 0 or Float(transfer_amount) != transfer_amount.to_i
raise Error, "请输入正确的转账金额"
end
transfer_amount = params['transfer_amount'].to_i transfer_amount = params['transfer_amount'].to_i
transfer_login = params['transfer_login'] transfer_login = params['transfer_login']
payer = params['payer_id'].to_s payer = params['payer_id'].to_s
payee = User.find_by(login: transfer_login) payee = User.find_by(login: transfer_login)
if payee.nil? if payee.nil?
# normal_status(-1, "未找到用户") raise Error, "未找到接收转账的用户"
return false
else else
payee = payee.id.to_s payee = payee.id.to_s
token_name = params['project_id'].to_s token_name = params['project_id'].to_s
# 调用token转移函数 # 调用token转移函数
results = transfer_balance_on_blockchain(payer, payee, token_name, transfer_amount) transfer_balance_on_blockchain(payer, payee, token_name, transfer_amount)
return results
end end
end end
rescue => e
puts "转账失败: #{e.message}"
# normal_status(-1, e.message)
return false
end end
private private
@ -34,4 +32,5 @@ class Blockchain::TransferService < ApplicationService
def no_use def no_use
puts "this function does not have any usage" puts "this function does not have any usage"
end end
end end