The Technicals of Interoperability—Introducing the Ethereum Peg Zone

Cosmos通过Peggy方案实现与Ethereum等非确定性区块链的资产转移。Peggy作为中介区块链,利用智能合约进行资产托管,并通过见证者验证交易的有效性,最终实现跨链资产转换。

Cross-blockchain crypto-asset transfer is core of what we do at Cosmos. Within the ecosystem, crypto-assets are transferred via the IBC protocol, an Inter-Blockchain Communication protocol, which facilitates interoperability. Notably, IBC only works if both the starting and the destination chains have settlement finality.

Fortunately or unfortunately, neither Bitcoin nor Ethereum have finality guarantees; rather, they have probabilistic finality. [Edit: for now Ethereum doesn’t benefit from the property of finality; until, that is, Casper the Friendly Finality Gadget (FFG) is implemented in the near-term future.] What this means is, the deeper down the chain a block is, the less likely the chain it’s on will get reorganized, giving you a high level of confidence that the block is “final”. But because probabilistic guarantees do not protect against reorgs, transferring assets securely across chains via IBC is impossible. This prompts the question: How can Cosmos zones interoperate with pre-existing blockchains absent finality?

Peg Zones

Peg zones are our solution. A peg zone is an account-based blockchain which bridges zones within Cosmos to external chains like Bitcoin or Ethereum. It acts as an adaptor zone — or a “finality gadget”, in Casper-speak — which translates finality for probabilistically finalized blockchains by imposing a “finality threshold” at some arbitrary number of blocks to achieve pseudo-finality. Generally, this “translator” zone design can be classified as a 2-way peg (2WP).

Consensus engines such as  Tendermint Core offer settlement finality. To better understand how it works, please read more about  Tendermint Consensus.

Connecting to Ethereum

An Ethereum peg zone is the first of its kind that we will be implementing in Cosmos. This is very different from Ethermint, which is the EVM, stripped of Proof-of-Work mining, then layered on top of Tendermint’s consensus and networking protocol stacks. The Ethereum peg zone will enable the movement of ERC20 tokens and Ether between the canonical Ethereum chain and all IBC-connected zones within the Cosmos Network.

The specifications for the peg zone are still being ironed out but you can follow the progress in the peg zone repository, codenamed peggy, linked below.

Peggy

In Cosmos, interoperability is easy because we can use the IBC protocol to transfer any crypto-asset. To transfer crypto-assets between Cosmos and Ethereum, however, is very technically complex because IBC packets cannot be efficiently decoded in Ethereum, simply because the EVM isn’t designed to be IBC-compatible. That is, until we implement Peggy.

Peggy had a rough start. The first construction that attempted to connect Cosmos to Ethereum was a hackathon project called ETGate, which turned out to be a gas guzzler. It was designed by Joon, the HackAtom 2 grand prize winner, who we ended up hiring to implement what is now Peggy.

ETGate initially was a direct bridge between the Cosmos Hub and Ethereum which attempted to translate compatibility within the EVM itself. Like so:

[ Ethereum ] <- ETGate -> [ Cosmos Hub ]

This design was highly impractical when confronted with the problem of the different building blocks used in Tendermint and Ethereum. Every primitive used in Tendermint is fundamentally different than that of Ethereum’s. Translating those incompatibilities into compatible, interpretable building blocks inside the EVM, it turns out, is incredibly gas costly.

Here’s the breakdown of those building blocks:

  • Serialization formats. Tendermint’s encoding method to serialize objects is go-wire. Ethereum serializes objects using RLP (Recursive Length Prefix).
  • Signature schemes. Tendermint uses ed25519 whereas Ethereum uses secp256k1.
  • Data structures. Tendermint stores key-values in IAVL+ trees while Ethereum stores them in Patricia Tries.

ETGate’s design was computationally expensive because it decoded IBC packets within the EVM, of which the contents were Tendermint’s headers, transactions, IAVL+ tree proofs, and ed25519 signatures.

The moment of clarity that led to the evolution of Peggy came from the realization that we could save significant amounts of gas by taking the translation mechanism out of the EVM and onto its own blockchain designed for this specific application.

Peggy’s 5 Components:
  1. Ethereum Smart Contracts: There will be a set of Ethereum smart contracts acting as asset custodians, capable of taking custody of Ethereum native tokens and issuing Cosmos native tokens.
  2. Witness: The witness component attests witness to events in Ethereum. It waits for 100 blocks, the finality threshold, and implements this pseudo-finality over the non-finality chain. It runs a fully validating Ethereum node in order to attest to state changes within Ethereum by submitting a WitnessTX to the peg zone. We use a shared security model here by taking the set of Cosmos Hub validators also to be peg zone Witnesses.
  3. Peg zone: The peg zone is a translator blockchain, built on Tendermint, that allows users to perform and query transactions. This is how Cosmos communicates with Ethereum.
  4. Signer: The signer signs messages using the secp256k1 signature scheme which Ethereum understands to make signatures efficiently verifiable by smart contracts. The signer component generates secp256k1 signatures via the SignTx message and posts it to the peg zone for relaying transactions for validation in the smart contract down the pipeline.
  5. Relayer: The relayer component relays a batched list (array) of transactions—signed by the Signer component—and posts them to the Ethereum smart contract.

Tying it All Together

Real World Example: Moving a Cosmos native token→Ethereum

Let’s say, for example, you want to move some quantity of Photons out of Cosmos and convert them to Ether of equal value on Ethereum. How would this work using Peggy? For simplicity’s sake, we’ll gloss over the low-level technical details and just describe the high-level flow.

  1. You start at the Cosmos Hub. You move Photons via IBC to the peg zone. The peg zone receives an incoming IBC packet: a message containing a transaction for sending Photons. Signers monitoring the peg zone then sign those IBC transactions, effectively converting the signature scheme to Ethereum-understandable private keys, in secp256k1 format. Your transaction has just been signed on the peg zone.
  2. Relayers watching the peg zone are waiting until they see that +2/3 signers have signed the transaction before batching your signed transaction into a list of all the other transactions sent through IBC. They then relay the signature-appended list to the EVM where the Ethereum smart contract lives.
  3. The Ethereum smart contract now checks that the list of transactions are valid. For your Photons, the smart contract needs to generate an ERC20 version of it. After the smart contract generates ERC20 Photons, it then sends the ERC20 Photons to your destination address in Ethereum.
  4. At this point, converting your ERC20 Photons to ETH is as simple as using an ERC20 decentralized exchange (DEX) like the 0x protocol or OmiseGO.

In Closing

We are currently prototyping a very early-stage Peggy design. The Ethereum smart contract component is already written and is currently being tested. In many ways, Peggy is even more technically complex than the Cosmos Hub itself and will take several iterations before we get it right. Cosmonauts can expect Peggy to go live sometime mid to late summer, well after mainnet launch. We understand that a lot is at stake and the need for scalability solutions, increased throughput, and decreased gas costs is important for Ethereum-based projects. Therefore, the deployment of Peggy is high priority and the Cosmos/Tendermint team has devoted a significant portion of its resources to its development in tandem with the rest of our ecosystem projects.

Ongoing Work

Ethereum smart contracts, once deployed, are immutable and therefore very difficult to update. There is a lack of organizational structure around governing smart contract upgrades. The development roadmap for Peggy compels us to confront this uncertainty but it’s an an area of research we hope will spawn concrete solutions.


原文: https://blog.cosmos.network/the-internet-of-blockchains-how-cosmos-does-interoperability-starting-with-the-ethereum-peg-zone-8744d4d2bc3f

def initialize(context): # 用户可修改参数设置 g.event_time = "9:30" # 触发时间,可设置范围是 09:30--11:29, 13:00--14:59 g.strategy_id = "88" # 策略ID g.buy_amount = 5000 # 单只股票买入金额 g.buy_count = 5 # 最大持仓数量(买入数量) g.holding_days = 4 # 持股周期(天数) g.buy_dates = {} # 记录买入日期 g.buy_pool = [] # 最终买入信息 g.sell_pool = [] # 最终卖出信息 run_daily(context, daily_event, time=g.event_time) # 设置触发时间 def before_trading_start(context, data): # 每天开盘前执行选股逻辑 # 1. 初步筛选:全市场 / 指数 / 板块 basic_pool = get_initial_pool(context) # 2. 基本面筛选 fundamental_pool = filter_by_fundamentals(basic_pool) # 3. 技术面筛选 technical_pool = filter_by_technicals(fundamental_pool, context) # 4. 综合评分排序 final_pool = comprehensive_ranking(fundamental_pool, technical_pool, context) # 5. 更新全局股票池 g.stock_pool = final_pool log.info("今日选股结果,共{}只股票:{}".format(len(g.stock_pool), g.stock_pool)) # 获取持仓股票集合 **** 以下所有内容,是不是考虑在交易环节去实现 yst_hold = {v.sid for s, v in get_positions().items()} # 获取今日股票池集合 today_pool = set(get_index_stocks('000300.XBHS')[:10]) # 使用集合运算:需要卖出的股票 = 持仓 - 今日股票池 g.sell_list = yst_hold - today_pool # 需要处理的股票 = 持仓 ∪ 今日股票池 g.sec_list = yst_hold | today_pool # 更新买入日期记录 current_date = context.current_dt.date() for stock in yst_hold: if stock not in g.buy_dates: g.buy_dates[stock] = current_date # 清理已卖出的股票记录 g.buy_dates = {k: v for k, v in g.buy_dates.items() if k in yst_hold} def daily_event(context): # 第一步:处理卖出 for stock in g.sell_pool: position = get_position(stock) # 取持仓数据 limit_up = check_limit(stock)[stock] == 1 # 检查是否涨停 current_date = context.blotter.current_dt.date() # 计算持股天数 holding_days = (current_date - g.buy_dates.get(stock, current_date)).days # 卖出逻辑 if (position.enable_amount > 0 and not limit_up) or holding_days >= g.holding_days: # 卖出条件1:(持仓 且 涨停不卖) 或 持股周期达到 if sell_signal1 or sell_signal2: # 卖出条件2:卖出信号出现 sell_signals volume = position.enable_amount order(stock, -volume) log.info(f'卖出 {stock}, 持股{holding_days}天, 收益{holdRet:.2%}') log.info(f'{check_limit(stock)[stock]} 涨停,暂停卖出,持股{holding_days}天') # 第二步:处理买入 current_hold_count = len([v for s, v in get_positions().items() if v.amount > 0]) # 获取当前持仓数量 for stock in g.buy_pool: position = get_position(stock) # 取持仓数据 limit_down = check_limit(stock)[stock] == -1 # 检查是否跌停 # 买入逻辑 if position.amount == 0 and holding_days >= g.holding_days and not limit_down: # 买入条件1:未持仓 且 未达到最大持仓数量 且 跌停不买 if buy_signal1 and buy_signal2: # 买入条件2:买入信号出现 buy_signals if stock[:3] != "688": volume = min(context.portfolio.cash, g.buy_amount) / position.last_sale_price // 100 * 100 # 计算买入数量并取整百,非科创 else: volume = min(context.portfolio.cash, g.buy_amount) / position.last_sale_price // 200 * 200 # 计算买入数量并取整百,科创 order(stock, volume) g.buy_dates[stock] = context.blotter.current_dt.date() # 更新买入日期 log.info(f'买入 {stock}, 数量{volume}, 金额{volume * position.last_sale_price:.2f}, 占资金{single_ratio:.2%}') log.info(f'计划持股{g.holding_days}天, 当前持仓{current_hold_count}只') def handle_data(context, data): pass 请在这个框架中进行修改,完成 持仓天数计算
10-12
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值