您正在查看: Other Chain 分类下的文章

Swarm激励模型合约

源代码:https://github.com/ethersphere/swap-swear-and-swindle

Swarm目前只跑在Goerli测试网,核心的合约为ERC20SimpleSwap,源代码在master分支,对于后续功能合约 full Swap, Swear and Swindle相关代码在experimental分支

逻辑简述

目前Swarm的Goerli测试网部署的合约逻辑为
用户通过执行SimpleSwapFactory合约,部署ERC20SimpleSwap合约,并与发行的gBZZ代币交互

用户与Swarm交互

测试用户

0x10210572d6b4924Af7Ef946136295e9b209E1FA0

部署ERC20SimpleSwap合约

用户地址通过执行SimpleSwapFactory合约的deploySimpleSwap方法,完成部署ERC20SimpleSwap合约,通过查看交易的eventlog,部署的Chequebook合约地址为0x68f7ea9f3fae55e3e55fee0f0761b7df570fd212

deploySimpleSwap合约代码

function deploySimpleSwap(address issuer, uint defaultHardDepositTimeoutDuration)
  public returns (address) {
    address contractAddress = address(new ERC20SimpleSwap(issuer, ERC20Address, defaultHardDepositTimeoutDuration));
    deployedContracts[contractAddress] = true;
    emit SimpleSwapDeployed(contractAddress);
    return contractAddress;
  }

deploySimpleSwap执行同时完成了ERC20SimpleSwap的构造初始化

constructor(address _issuer, address _token, uint _defaultHardDepositTimeout) public {
    issuer = _issuer;
    token = ERC20(_token);
    defaultHardDepositTimeout = _defaultHardDepositTimeout;
  }

同时初始化了交互Token gBZZ代币

订金(为支票薄提供资金)

通过执行API进行为支票薄提供资金
http://localhost:1635/chequebook/deposit?amount=1000000000
执行的逻辑为用户地址0x10210572d6b4924af7ef946136295e9b209e1fa0向自己的Chequebook合约地址0x68f7ea9f3fae55e3e55fee0f0761b7df570fd212转对应数量的gBZZ,也可以理解成充值抵押

测试交易

https://goerli.etherscan.io/tx/0x81080bdc2ee4ede8898f003c4b74c9dcabdd6467e443f9ab8669f0c62434aaee

提现

将自己Chequebook合约中的gBZZ体现到用户地址
执行逻辑为执行自己的Chequebook合约地址0x68f7ea9f3fae55e3e55fee0f0761b7df570fd212中的withdraw方法。

合约代码

function withdraw(uint amount) public {
    /* 只有发行人可以做到这一点 */
    require(msg.sender == issuer, "not issuer");
    /* 确保我们不从保证金中提取任何东西 */
    require(amount <= liquidBalance(), "liquidBalance not sufficient");
    require(token.transfer(issuer, amount), "transfer failed");
  }

测试交易

https://goerli.etherscan.io/tx/0x967fabac2da76d868a9f80d8a64baacbe2cb585519388a4494593705ef050421

分析ERC20SimpleSwap合约

// SPDX-License-Identifier: BSD-3-Clause
pragma solidity =0.7.6;
pragma abicoder v2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/presets/ERC20PresetMinterPauser.sol";


/**
@title支票簿合同,无豁免
@author The Swarm作者
@notice支票簿合同允许支票簿的发行者将支票发送到无限数量的交易对手。
此外,可以通过hardDeposits保证偿付能力
@dev作为发行人,如果发送的支票的累积价值高于所有存款的累积价值,则不应该发送任何支票
作为受益人,我们应始终考虑支票弹跳的可能性(当未分配hardDeposits时)
*/
contract ERC20SimpleSwap {
  using SafeMath for uint;

  event ChequeCashed(
    address indexed beneficiary,
    address indexed recipient,
    address indexed caller,
    uint totalPayout,
    uint cumulativePayout,
    uint callerPayout
  );
  event ChequeBounced();
  event HardDepositAmountChanged(address indexed beneficiary, uint amount);
  event HardDepositDecreasePrepared(address indexed beneficiary, uint decreaseAmount);
  event HardDepositTimeoutChanged(address indexed beneficiary, uint timeout);
  event Withdraw(uint amount);

  uint public defaultHardDepositTimeout;
  /* 跟踪每个受益人的硬存款(偿付能力的链上保证)的结构*/
  struct HardDeposit {
    uint amount; /* 分配的硬存款金额 */
    uint decreaseAmount; /* 减少量从请求减少时的金额中减去 */
    uint timeout; /* 发行者必须等待超时秒数才能减少hardDeposit,0表示应用defaultHardDepositTimeout */
    uint canBeDecreasedAt; /* 可以减少硬质沉积的时间点 */
  }

  struct EIP712Domain {
    string name;
    string version;
    uint256 chainId;
  }

  bytes32 public constant EIP712DOMAIN_TYPEHASH = keccak256(
    "EIP712Domain(string name,string version,uint256 chainId)"
  );
  bytes32 public constant CHEQUE_TYPEHASH = keccak256(
    "Cheque(address chequebook,address beneficiary,uint256 cumulativePayout)"
  );
  bytes32 public constant CASHOUT_TYPEHASH = keccak256(
    "Cashout(address chequebook,address sender,uint256 requestPayout,address recipient,uint256 callerPayout)"
  );
  bytes32 public constant CUSTOMDECREASETIMEOUT_TYPEHASH = keccak256(
    "CustomDecreaseTimeout(address chequebook,address beneficiary,uint256 decreaseTimeout)"
  );

  // 该合同使用的EIP712域
  function domain() internal pure returns (EIP712Domain memory) {
    uint256 chainId;
    assembly {
      chainId := chainid()
    }
    return EIP712Domain({
      name: "Chequebook",
      version: "1.0",
      chainId: chainId
    });
  }

  // 计算EIP712域分隔符。 这不能恒定,因为它取决于chainId
  function domainSeparator(EIP712Domain memory eip712Domain) internal pure returns (bytes32) {
    return keccak256(abi.encode(
        EIP712DOMAIN_TYPEHASH,
        keccak256(bytes(eip712Domain.name)),
        keccak256(bytes(eip712Domain.version)),
        eip712Domain.chainId
    ));
  }

  // 使用EIP712签名方案恢复签名
  function recoverEIP712(bytes32 hash, bytes memory sig) internal pure returns (address) {
    bytes32 digest = keccak256(abi.encodePacked(
        "\x19\x01",
        domainSeparator(domain()),
        hash
    ));
    return ECDSA.recover(digest, sig);
  }

  /* 此支票簿针对其写支票的令牌 */
  ERC20 public token;
  /* 将每个受益人与已支付给他们的款项相关联 */
  mapping (address => uint) public paidOut;
  /* 支付总额 */
  uint public totalPaidOut;
  /* 将每个受益人与他们的HardDeposit相关联 */
  mapping (address => HardDeposit) public hardDeposits;
  /* 所有硬存款的总和 */
  uint public totalHardDeposit;
  /* 合同的签发人,在施工中 */
  address public issuer;
  /* 指示支票是否在过去退回 */
  bool public bounced;

  /**
  @notice设置颁发者,令牌和defaultHardDepositTimeout。 只能被调用一次。
   @param _issuer此支票簿的支票的发行者(需要作为“将支票簿设置为付款”的参数)。
   _issuer必须是外部拥有的帐户,或者它必须支持调用函数cashCheque
   @param _token此支票簿使用的令牌
   @param _defaultHardDepositTimeout持续时间(以秒为单位),默认情况下将用于减少hardDeposit分配
  */
  function init(address _issuer, address _token, uint _defaultHardDepositTimeout) public {
    require(_issuer != address(0), "invalid issuer");
    require(issuer == address(0), "already initialized");
    issuer = _issuer;
    token = ERC20(_token);
    defaultHardDepositTimeout = _defaultHardDepositTimeout;
  }

  /// @return 支票簿的余额
  function balance() public view returns(uint) {
    return token.balanceOf(address(this));
  }
  /// @return 余额中没有硬存款支付的部分
  function liquidBalance() public view returns(uint) {
    return balance().sub(totalHardDeposit);
  }

  /// @return 余额中可用于特定受益人的部分
  function liquidBalanceFor(address beneficiary) public view returns(uint) {
    return liquidBalance().add(hardDeposits[beneficiary].amount);
  }
  /**
  @dev内部函数负责检查issuerSignature,更新hardDeposit余额并进行转账。
   由CashCheque和CashChequeBeneficary调用
   @param受益人支票分配给的受益人。 受益人必须是外部拥有的帐户
   @param接收者会收到累计付款与已付给受益人减去调用者的款项之间的差额
   @paramcumulativePayout分配给受益人的累计支票数量
   @param issuerSig如果发行人不是发件人,则发行人必须已在累计付款上明确授予受益人
  */
  function _cashChequeInternal(
    address beneficiary,
    address recipient,
    uint cumulativePayout,
    uint callerPayout,
    bytes memory issuerSig
  ) internal {
    /* 发行人必须通过作为主叫方或通过签名明确批准累计支付 */
    if (msg.sender != issuer) {
      require(issuer == recoverEIP712(chequeHash(address(this), beneficiary, cumulativePayout), issuerSig),
      "invalid issuer signature");
    }
    /* requestPayout是请求进行付款处理的金额 */
    uint requestPayout = cumulativePayout.sub(paidOut[beneficiary]);
    /* 计算实际支出 */
    uint totalPayout = Math.min(requestPayout, liquidBalanceFor(beneficiary));
    /* 计算硬存款使用量 */
    uint hardDepositUsage = Math.min(totalPayout, hardDeposits[beneficiary].amount);
    require(totalPayout >= callerPayout, "SimpleSwap: cannot pay caller");
    /* 如果有一些使用的硬存款,请更新hardDeposits */
    if (hardDepositUsage != 0) {
      hardDeposits[beneficiary].amount = hardDeposits[beneficiary].amount.sub(hardDepositUsage);

      totalHardDeposit = totalHardDeposit.sub(hardDepositUsage);
    }
    /* 增加存储的payedOut金额以避免双倍支付 */
    paidOut[beneficiary] = paidOut[beneficiary].add(totalPayout);
    totalPaidOut = totalPaidOut.add(totalPayout);

    /* 让全世界知道发行人对未兑现支票的承诺过高 */
    if (requestPayout != totalPayout) {
      bounced = true;
      emit ChequeBounced();
    }

    if (callerPayout != 0) {
    /* 如果指定,则转接到呼叫者 */
      require(token.transfer(msg.sender, callerPayout), "transfer failed");
      /* 进行实际付款 */
      require(token.transfer(recipient, totalPayout.sub(callerPayout)), "transfer failed");
    } else {
      /* 进行实际付款 */
      require(token.transfer(recipient, totalPayout), "transfer failed");
    }

    emit ChequeCashed(beneficiary, recipient, msg.sender, totalPayout, cumulativePayout, callerPayout);
  }
  /**
  @notice兑现非受益人的受益人支票,并通过发送方与发件人奖励这样做
  @dev受益人必须能够生成签名(作为外部拥有的帐户)才能使用此功能
  @param受益人支票分配给的受益人。受益人必须是外部拥有的帐户
  @param接收者会收到累计付款与已付给受益人减去调用者的款项之间的差额
  @paramcumulativePayout分配给受益人的累计支票数量
  @param受益人Sig受益人必须已经明确批准才能由发件人兑现累计付款并发送给callerPayout
  @param issuerSig如果发行人不是发件人,则发行人必须已在累计付款上明确授予受益人
  @param callerPayout当受益人还没有以太币时,他可以在callerPayout的帮助下激励其他人兑现支票
  @param issuerSig如果发行人不是发件人,则发行人必须已在累计付款上明确授予受益人
  */
  function cashCheque(
    address beneficiary,
    address recipient,
    uint cumulativePayout,
    bytes memory beneficiarySig,
    uint256 callerPayout,
    bytes memory issuerSig
  ) public {
    require(
      beneficiary == recoverEIP712(
        cashOutHash(
          address(this),
          msg.sender,
          cumulativePayout,
          recipient,
          callerPayout
        ), beneficiarySig
      ), "invalid beneficiary signature");
    _cashChequeInternal(beneficiary, recipient, cumulativePayout, callerPayout, issuerSig);
  }

  /**
  @注意兑现支票作为受益人
   @param接收者会收到累计付款与已付给受益人减去调用者的款项之间的差额
   @param的累计付款要求付款
   @param issuerSig发行者必须已对收款人的累计付款给予明确批准
  */
  function cashChequeBeneficiary(address recipient, uint cumulativePayout, bytes memory issuerSig) public {
    _cashChequeInternal(msg.sender, recipient, cumulativePayout, 0, issuerSig);
  }

  /**
  @注意准备减少硬沉积
   @dev减少hardDeposit必须分两步完成,以使受益人兑现任何未兑现的支票(并利用相关的硬存款)
   @param受益人,应减少其硬存款
   @param reduction存款应减少的金额
  */
  function prepareDecreaseHardDeposit(address beneficiary, uint decreaseAmount) public {
    require(msg.sender == issuer, "SimpleSwap: not issuer");
    HardDeposit storage hardDeposit = hardDeposits[beneficiary];
    /* 如果减少的幅度超过存款,则不能减少 */
    require(decreaseAmount <= hardDeposit.amount, "hard deposit not sufficient");
    // 如果从未设置hardDeposit.timeout,则应用defaultHardDepositTimeout
    uint timeout = hardDeposit.timeout == 0 ? defaultHardDepositTimeout : hardDeposit.timeout;
    hardDeposit.canBeDecreasedAt = block.timestamp + timeout;
    hardDeposit.decreaseAmount = decreaseAmount;
    emit HardDepositDecreasePrepared(beneficiary, decreaseAmount);
  }

  /**
  @notice自调用prepareDecreaseHard存款以来等待了必要的时间后,减少了硬存款
  @param受益人,应减少其硬存款
  */
  function decreaseHardDeposit(address beneficiary) public {
    HardDeposit storage hardDeposit = hardDeposits[beneficiary];
    require(block.timestamp >= hardDeposit.canBeDecreasedAt && hardDeposit.canBeDecreasedAt != 0, "deposit not yet timed out");
    /* this throws if decreaseAmount > amount */
    //TODO: 如果prepareDecreaseHardDeposit和reducedHardDeposit之间有现金兑现,那么reducingHardDeposit将抛出并且无法减少硬存款。
    hardDeposit.amount = hardDeposit.amount.sub(hardDeposit.decreaseAmount);
    /* 重置canBeDecreasedAt以避免两次减少 */
    hardDeposit.canBeDecreasedAt = 0;
    /* 保持totalDeposit同步 */
    totalHardDeposit = totalHardDeposit.sub(hardDeposit.decreaseAmount);
    emit HardDepositAmountChanged(beneficiary, hardDeposit.amount);
  }

  /**
  @注意增加硬保证金
   @param受益人,应减少其硬存款
   @param金额新的硬存款
  */
  function increaseHardDeposit(address beneficiary, uint amount) public {
    require(msg.sender == issuer, "SimpleSwap: not issuer");
    /* 确保保证金不超过全球余额 */
    require(totalHardDeposit.add(amount) <= balance(), "hard deposit exceeds balance");

    HardDeposit storage hardDeposit = hardDeposits[beneficiary];
    hardDeposit.amount = hardDeposit.amount.add(amount);
    // 我们没有明确设置hardDepositTimout,因为零意味着使用默认的HardDeposit超时
    totalHardDeposit = totalHardDeposit.add(amount);
    /* 禁用任何未决的减少 */
    hardDeposit.canBeDecreasedAt = 0;
    emit HardDepositAmountChanged(beneficiary, hardDeposit.amount);
  }

  /**
 @notice允许为每个受益人设置自定义的hardDepositDecreaseTimeout
   @dev,当必须保证偿付能力的时间长于defaultHardDepositDecreaseTimeout时,这是必需的
   @param收款人的硬存款减少的受益人必须更改超时
   @param hardDepositTimeout受益人新的hardDeposit.timeout
   @param受益人Sig受益人必须通过在新的reduceTimeout上签名来明确批准
  */
  function setCustomHardDepositTimeout(
    address beneficiary,
    uint hardDepositTimeout,
    bytes memory beneficiarySig
  ) public {
    require(msg.sender == issuer, "not issuer");
    require(
      beneficiary == recoverEIP712(customDecreaseTimeoutHash(address(this), beneficiary, hardDepositTimeout), beneficiarySig),
      "invalid beneficiary signature"
    );
    hardDeposits[beneficiary].timeout = hardDepositTimeout;
    emit HardDepositTimeoutChanged(beneficiary, hardDepositTimeout);
  }

  /// @notice提取以太币
   /// @param要提取的金额
   // solhint-disable-next-line no-simple-event-func-name
  function withdraw(uint amount) public {
    /* 只有发行人可以做到这一点 */
    require(msg.sender == issuer, "not issuer");
    /* 确保我们不从保证金中提取任何东西 */
    require(amount <= liquidBalance(), "liquidBalance not sufficient");
    require(token.transfer(issuer, amount), "transfer failed");
  }

  function chequeHash(address chequebook, address beneficiary, uint cumulativePayout)
  internal pure returns (bytes32) {
    return keccak256(abi.encode(
      CHEQUE_TYPEHASH,
      chequebook,
      beneficiary,
      cumulativePayout
    ));
  }  

  function cashOutHash(address chequebook, address sender, uint requestPayout, address recipient, uint callerPayout)
  internal pure returns (bytes32) {
    return keccak256(abi.encode(
      CASHOUT_TYPEHASH,
      chequebook,
      sender,
      requestPayout,
      recipient,
      callerPayout
    ));
  }

  function customDecreaseTimeoutHash(address chequebook, address beneficiary, uint decreaseTimeout)
  internal pure returns (bytes32) {
    return keccak256(abi.encode(
      CUSTOMDECREASETIMEOUT_TYPEHASH,
      chequebook,
      beneficiary,
      decreaseTimeout
    ));
  }
}

Cash Cheque Beneficiary

https://goerli.etherscan.io/tx/0x6e255bcd2eb2a84d2a80e25368413f805a036d3cea18d43c81e96f0158a3084c

ETH 2.0技术调研

Chia 分布式部署详细文档

最近社区很多小伙伴来询问Chia分布式部署的方法,那我们今天就写一下Chia分布式的步骤以及测试环境验证

分布式的逻辑

其实前面已经写过部署的草稿了《Chia 分布式部署文档》,但是由于当时时间紧,对于没有开发基础的小伙伴理解上还是有些难度。
下面我们详细说下分布式拆分原理以及注意事项

下面是Chia架构模块结构


简单说每个模块都是单独的程序,都是通过TCP连接的,对于Chia Gui程序,默认运行是把各个模块都运行在本地,localhost连接的。对于分布式来说,就是把各个模块根据功能和负载等因素分不到不同机器。

模拟生产环境

由于plots存储量体量无上限,并且数据可重新生成,对于存储量和数据安全来说,优先选择存储量,所以单盘存储,不做raid。
对于专门做Chia挖矿的,一般的硬件配置是搞一部分配置稍微好的机器做P盘机(绘图机/work机..){稍后会专门写一篇推荐生产P盘配置的文章},一些二手的存储机做存储(服务器前部分是磁盘阵列),P盘机硬件配置存储部分只有SSD临时绘图用,最终的plots存储到存储机《为Chia P盘机器提供存储服务

此篇文章我们主要讲挖矿的分布式,对于P盘自动化,后面会有专门的程序和文章做讲解。

生产环境中,一般是把所有的机器放到一个IDC机房,或者自己来管理,所以模块内服务器都是内网连接,网络环境相对简单。

中控高度可控

对于系统化架构的设计大致如下,各模块彼此低耦合,对于一台机器只要装上中控子服务,配置好Chia中控调度地址,Chia中控调度服务会自动配置该机器的环境,并自动下发相应的任务,减少用户的学习成本。
也可以用于推广绘图算力和绘图存储,
用户只需要安装对应中控子服务(绘图/存储),Chia中控调度中心即可自动下发对应的任务,对于绘图任务类似POW,根据用户绘图量用户得到相应的奖励。
用户也可以选择存储任务,此时中控子服务会下发已经会好的图,用户无感知,只需要准备好足够容量的存储空间即可,子服务会自动安装好Harvester相关服务配置,中控调度只需要定时检查用户存储状态和网络环境,就可以根据工作量进行奖励发放。当然发放的可以别的链的对应代币,可以用于对冲推广代币等。
只是对调度服务的另一个使用场景吧,


后面社区也许会推出整体服务,暂时不确定

对于没有开发能力的,架构中的中控服务可以先用人工来代替

简化后架构如下


对于各模块的增改也先人工处理

实际测试

我们来演示最基础的分布式挖矿配置,一台挖矿服务器和两台存储服务器之前的配置,以及验证配置是否正确。

稍后继续补充

Chia 源代码编译安装

操作系统

Ubuntu 20.04

编译

sudo apt-get update
sudo apt-get upgrade -y

# Checkout the source and install
git clone https://github.com/Chia-Network/chia-blockchain.git -b latest
cd chia-blockchain

sh install.sh

. ./activate

# The GUI requires you have Ubuntu Desktop or a similar windowing system installed.
# You can not install and run the GUI as root

sh install-gui.sh

cd chia-blockchain-gui
npm run electron &

升级

cd chia-blockchain
chia stop -d all
deactivate
git fetch
git checkout latest
git pull

# If you get RELEASE.dev0 then delete the package-lock.json in chia-blockchain-gui and install.sh again

sh install.sh

. ./activate

chia init

# The GUI requires you have Ubuntu Desktop or a similar windowing system installed.
# You can not install and run the GUI as root

sh install-gui.sh

cd chia-blockchain-gui
npm run electron &

参考

https://github.com/Chia-Network/chia-blockchain/wiki/INSTALL#ubuntudebian