# @Time : 18-10-28 上午10:11 import time from source import config from source.poll.base import get_tb_balance from source.common.utils.log import get_logger from source.common.chain_driver.bitcoin_operator import BtcOP from source.common.chain_driver.bitcoin_operator.usdt import USDTOP from source.model.database import ( Gather, AccountBalance, AskFeeStatusEnum, AskFee ) coin_type = 'USDT' logger = get_logger('gather-usdt') def ask_fee(address): """usdt转账使用btc作为手续费.""" rv = AskFee.find_one({'coin_type': 'BTC', 'to_address': address, 'status': AskFeeStatusEnum.ASKING}) if not rv: record = { 'coin_type': 'BTC', 'to_address': address, 'amount': config.usdt_fee_min } AskFee(**record).insert()
# -*- coding: utf-8 -*- # @File : update_balance.py # @Author : lh import time from source import config from source.common.chain_driver.xlm import XlmOP from source.common.utils.log import get_logger from source.model.database import AccountBalance from datetime import datetime logger = get_logger('update-xlm_poll-balance') class UpdateBalance: def update_balance(self): xlm = XlmOP(config, config.xlm_cb_url) tb_balance = xlm.get_balance(config.xlm_tb_address) record = { 'coin_type': 'XLM', 'updated_at': datetime.utcnow(), 'balance': float(tb_balance) } AccountBalance.find_one_and_update({'coin_type': 'XLM'}, record) def poll(self): logger.info(f'-----update balance start----------') while True: try: self.update_balance()
# -*- coding: utf-8 -*- # @File : withdraw_poll.py # @Author : lh # 提币检测 import time from source import config from source.common.chain_driver.xlm import XlmOP from source.poll.base import CheckWithdraw from source.common.utils.log import get_logger from source.model.database import TbRecord, TbStatusEnum coin_type = 'XLM' default_interval = 10 logger = get_logger('check-xlm_poll-tb') class CheckWithDraw: def check_withdraw(self): res_list = TbRecord.find({ 'coin_type': coin_type, 'status': TbStatusEnum.TRANSFER }) xlm = XlmOP(config, config.xlm_tb_url) for each in res_list: tx_id = each['id'] tx_res = xlm.get_trans_info(tx_id) tx_ledger = tx_res.get('ledger') # 获取当前最新区块数 ledger_res = xlm.get_ledgers() new_ledger = ledger_res[0]['sequence']
# @Author : ymy # @Email : [email protected] # @Time : 18-11-10 上午10:28 from datetime import datetime from source.poll import rpc_call from source.common.utils.log import get_logger from source.model.database import ( TbRecord, TbStatusEnum, InformEnum, Recharge, RechargeStatusEnum, AccountBalance ) logger = get_logger('update-withdraw-status') class Base(object): __type__ = ('withdraw', 'recharge') def __init__(self, item, confirmations, _type): assert _type in Base.__type__ self.item = item self.confirmations = confirmations self.type = _type @property def success(self): if self.type == 'withdraw': return TbStatusEnum.SUCCESS else:
import enum import json import datetime from copy import deepcopy from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import (Column, String, DateTime, Boolean, Integer, Enum, Text, create_engine, Index, BINARY, FLOAT) from source import config from source.common.utils.log import get_logger Base = declarative_base() engine = create_engine(config.database_uri) Session = sessionmaker(bind=engine) logger = get_logger('database') def default(o): if type(o) is datetime.date or type(o) is datetime.datetime: return o.isoformat() class MyBase(Base): __abstract__ = True def __init__(self, **kwargs): """ 兼容mongodb的习惯写法. 如: >>> data = {'account': '20180112', 'pub_address': '0xabc'}
# @Email : [email protected] # @Time : 19-1-31 import abc from source import config from source.poll.wallet_interface import WalletInterface from source.common.chain_driver.erc20_operator.erc20 import ERC20Token, ERC20TokenChild, TransactionManager from source.model.records import CoinSettingRecord, BlockInfoRecord, RecordNotFound from source.model.database import Account from source.common.chain_driver.utils import JSONRPCException from web3.utils.validation import validate_address from web3.utils.encoding import hexstr_if_str, to_hex from source.common.utils.log import get_logger EmptyTransaction = dict(confirmations=0) logger = get_logger('eth-wallet') class WalletImpl(WalletInterface): CoinSettingRecord = CoinSettingRecord Account = Account def __init__(self, configure): self.coin_type = configure.coin_type self.block_record = BlockInfoRecord(configure) self.token_address = CoinSettingRecord(configure).token_address self.wallet_op = ERC20Token() self.tb_address = configure.tb_address self.confirmation_count = configure.confirmation_count try: self.block_num, self.block_hash = self.block_record.retrieve_head_block(
# @Author : xy.zhang # @Email : [email protected] # @Time : 19-1-31 import abc import copy from source.poll.wallet_interface import WalletInterface from source.common.chain_driver.bitcoin_operator import USDTOP from source.model.database import Account from source.common.chain_driver.utils import JSONRPCException from source.common.utils.log import get_logger PROPERTY_ID = 31 EmptyTransaction = dict(confirmations=0) logger = get_logger("qtum-wallet") class WalletImpl(WalletInterface): def __init__(self, configure): self.coin_type = configure.coin_type self.wallet_op = USDTOP(configure.rpc_uri, timeout=configure.timeout) def list_transactions(self): trans = self.wallet_op.list_transactions() if not trans: raise StopIteration for tran in trans: tran['address'] = tran['referenceaddress'] yield tran def list_transactions_in(self):
# @Author : xy.zhang # @Email : [email protected] # @Time : 19-1-29 import time from source import config from decimal import Decimal from source.common.utils.log import get_logger from source.model.records import RechargeRecord from source.poll.wallets import WalletRecharge from source.model.database import RechargeStatusEnum, InformEnum logger = get_logger('recharge-poll') # 业务逻辑: # 1. 轮询询区块链上所有的充值本钱包的交易记录 ( transaction ) # 2. 检查当前交易是否已记入表内,如果未记入表内则插入一条记录 # 3. 如果当前交易确认数有变化 并且当前交易未经通知 Java # 4. 检查当前交易是否被取消( abandoned ? ) # 5. 检测当前交易确认数是否足够 ( >= confirm_cnt_touchstone ? ) # 6. 通知 JAVA 确认数有变化 和 交易的最终状态 # Recharge wallet # DEBUG:source.common.chain_driver.utils:-1-> getnewaddress ["QTUM_20190213_0_1550045763.492328"] # DEBUG:source.common.chain_driver.utils:<-1- "qJkRgdNg65x41P5friw6sJQS4iLzoEtknE" # DEBUG:source.common.chain_driver.utils:-2-> dumpprivkey ["qJkRgdNg65x41P5friw6sJQS4iLzoEtknE"] # DEBUG:source.common.chain_driver.utils:<-2- "cNMbrjecRwexmSpQLqRVBPvGEJL3pxQDBDWCbhsJ5Hqoss1GVEen" # Withdraw Wallet # WARNING:root:item:database_uri not in qtum.json, try env # DEBUG:source.common.chain_driver.utils:-1-> getnewaddress ["QTUM_20190214_0_1550131852.770854"]
@author:ljc @file: etc.py @time: 2018/11/01 """ from web3.utils.encoding import (hexstr_if_str, to_hex) from source import config from source.common.utils.log import get_logger from source.common.chain_driver.erc20_operator.erc20 import ERC20Token from source.common.chain_driver.erc20_operator.utils.keyfile_op import load_keyfile from source.model.database import Session, TbRecord from source.common.address_manager import EtcManager from . import BaseAPI logger = get_logger(__name__) class Etc(BaseAPI): def __init__(self): super().__init__("ETC") def get_address(self): manager = EtcManager(Session) address = manager.get_address() return { "pub_address": address.get("pub_address", ""), "tag": address.get("destination_tag", "") } def send2address(self, address, amount, *args, **kwargs):
# @Author : xy.zhang # @Email : [email protected] # @Time : 19-1-29 import os import json from source.common.utils.log import get_logger import os logger = get_logger('wallet-config') NECESSARY_ENV = ["wallet_user", "wallet_password", "database_uri", "rpc_host", "rpc_port", "coin_type"] class WalletConfig: def __init__(self, coin_type, coin_category): self.coin_type = coin_type.lower() self.coin_category = coin_category.lower() if coin_category else None cwd = os.path.dirname(os.path.abspath(__file__)) self.config_json = None with open(f"{cwd}/{self.coin_type}.json") as f: json_str = f.read() self.config_json = json.loads(json_str) if self.config_json['production']: for env_name in NECESSARY_ENV: try: del self.config_json[env_name]
# 充币检测 import time from datetime import datetime from source import config from source.poll import rpc_call from source.poll.base import CheckRecharge from source.common.utils.log import get_logger from source.common.chain_driver.bitcoin_operator.usdt import USDTOP from source.model.database import (Recharge, Account, RechargeStatusEnum, RegisterEnum, AccountBalance, InformEnum) coin_type = 'USDT' property_id = 31 logger = get_logger('recharge-usdt') def update_address_balance(): rv = Recharge.find_one({ 'coin_type': coin_type, 'register': RegisterEnum.NO }) for each in rv: address = each['to_address'] amount = rv['amount'] res = Recharge.find_one({'coin_type': coin_type, 'address': address}) if res: record = { 'address': address, 'balance': amount,
# -*- coding: utf-8 -*- # @File : xlm_poll.py # @Author : lh # @time : 18-11-12 下午8:47 from source import config from source.common.utils.log import get_logger from . import BaseAPI from source.model.database import TbRecord, Session from source.model.address_manager import XlmManager from source.common.chain_driver.xlm import XlmOP logger = get_logger('xlm_poll-withdraw') class XLM(BaseAPI): def __init__(self): super().__init__("XLM") def get_address(self): # 生成地址 manager = XlmManager(Session) address = manager.get_address() bind_address = { 'pub_address': address['pub_address'], 'destination_tag': address['destination_tag'] } return bind_address def send2address(self, address, amount, destination_tag, **kwargs): # 提币接口 from_address = config.xlm_tb_address
# @Author : ymy # @Email : [email protected] # @Time : 18-10-28 上午10:53 import time from source import config from source.common.utils.log import get_logger from source.model.database import Gather, GatherStatusEnum from source.common.chain_driver.bitcoin_operator.usdt import USDTOP coin_type = 'USDT' logger = get_logger('check-gather-usdt') def check(): usdt = USDTOP(config.usdt_rpc_uri, config.timeout) record = Gather.find({ 'coin_type': coin_type, 'status': GatherStatusEnum.GATHER }) for each in record: tx_id = each['txid'] rv = usdt.get_transaction(tx_id) each['fee'] = rv.get('fee') each['fee_coin'] = coin_type confirmation_count = rv.get('confirmation_count') each['confirmation_count'] = confirmation_count if confirmation_count > config.usdt_confirmation: each['status'] = GatherStatusEnum.SUCCESS if rv.get('abandoned', False):
# -*- coding: utf-8 -*- # @File : gather_tx_poll.py # @Author : lh import time import traceback from source import config from source.common.utils.log import get_logger from source.model.database import Gather, GatherStatusEnum from source.common.chain_driver.xlm import XlmOP coin_type = 'XLM' logger = get_logger('check-gather-xlm_poll') class CheckGather: def check_gather_tx(self): xlm = XlmOP(config, config.xlm_tb_url) rec_list = Gather.find({ 'coin_type': coin_type, 'status': GatherStatusEnum.GATHER }) try: for each in rec_list: tx_id = each['txid'] res = xlm.get_trans_info(tx_id) each['fee'] = res.get('fee_paid') each['fee_coin'] = coin_type # 最新区块数减去创建交易所在区块的差值当作确认数 trans_ldger = res.get('')
# @Author : ymy # @Email : [email protected] # @Time : 18-11-7 下午7:57 from datetime import datetime from source import config from source.common.utils.log import get_logger from source.model.database import AccountBalance from source.common.chain_driver.bitcoin_operator.usdt import USDTOP logger = get_logger('update-usdt-balance') def update(): usdt = USDTOP(config.usdt_rpc_uri, config.timeout) tb_balance = usdt.get_address_balance(config.usdt_tb_address) record = { 'coin_type': 'USDT_TX', 'updated_at': datetime.utcnow(), 'balance': float(tb_balance) } AccountBalance.find_one_and_update({'coin_type': 'USDT_TX'}, record) if __name__ == '__main__': while True: try: update() except Exception as e: logger.exception(e)
# -*- coding: utf-8 -*- # @File : recharge_poll.py # @Author : lh import time from source import config from datetime import datetime from source.poll import rpc_call from source.poll.base import CheckRecharge from source.common.utils.log import get_logger from source.common.chain_driver.xlm import XlmOP from source.model.database import (Recharge, Account, RechargeStatusEnum, RegisterEnum, AccountBalance, InformEnum) coin_type = 'XLM' logger = get_logger('recharge-xlm_poll') class CheckRechargePoll: def check_recharge(self): """ 充币检测 """ xlm = XlmOP(config, config.xlm_tb_url) # 获取oplsit logger.info('*' * 20) res_list = xlm.get_operations(config.xlm_cb_address) for each in res_list: logger.info(f'交易xinxi{each}+++++') tx_id = each['transaction_hash'] # 根据交易id获取memo
import json # from source import config from stellar_base.builder import Builder from stellar_base.horizon import horizon_livenet, horizon_testnet from stellar_base.keypair import Keypair from stellar_base.memo import TextMemo from stellar_base.operation import CreateAccount from stellar_base.transaction import Transaction from stellar_base.transaction_envelope import TransactionEnvelope from stellar_base.utils import StellarMnemonic from stellar_base.address import Address from stellar_base.horizon import Horizon from source.common.utils.log import get_logger logger = get_logger('create-account-xlm_poll') class XlmOP: def __init__(self, rpc_uri, timeout): self.client = Horizon(horizon=rpc_uri, timeout=timeout) # 测试节点 self.rpc_uri = rpc_uri # self.client = Horizon(horizon=horizon_livenet()) # 正式链 def generate_pri_keys(self): """ 生成随机公钥私钥 """ # sm = StellarMnemonic() # secret_phrase = sm.generate() # kp = Keypair.deterministic(secret_phrase)
""" import datetime from decimal import Decimal, ROUND_DOWN import time from web3 import Web3 from source import config from source.common.utils import log from source.common.chain_driver.erc20_operator.erc20 import ERC20Token from source.common.chain_driver.erc20_operator.const import DEFAULT_GAS_PRICE from source.model.database import Session, GatherStatusEnum, AskFeeStatusEnum from .base import ErcTxPoll logger = log.get_logger(__name__, config.log_level) Fail = -1 class AskFeeTxPoll(ErcTxPoll): """ 缴费交易状态检测轮寻 """ @staticmethod def check_success(operator: ERC20Token, item): """检查是否成功 :param operator: 区块链接口 :param item: 交易信息 :return:
# @Author : ymy # @Email : [email protected] # @Time : 18-10-28 下午12:04 import time from source import config from source.poll.base import CheckWithdraw from source.common.utils.log import get_logger from source.common.chain_driver.bitcoin_operator.usdt import USDTOP from source.model.database import TbRecord, TbStatusEnum, InformEnum coin_type = 'USDT' logger = get_logger('check-withdraw-usdt') def check(): res = TbRecord.find({'coin_type': coin_type, 'status': TbStatusEnum.TRANSFER}) usdt = USDTOP(config.usdt_rpc_uri, config.timeout) for each in res: tx_id = each['txid'] tx_detail = usdt.get_transaction(tx_id) confirmation_count = tx_detail.get('confirmation_count') cw = CheckWithdraw(each, config.usdt_confirmation) cw.update_confirmations(confirmation_count) if __name__ == '__main__': while True: