Skip to content

Commit

Permalink
Merge pull request #26 from nervosnetwork/shaojunda-add-mature-block-…
Browse files Browse the repository at this point in the history
…range-sample

feat: add GetMaxMatureBlockNumber func
  • Loading branch information
shaojunda authored Apr 8, 2021
2 parents 1d98786 + b607158 commit 4d76309
Show file tree
Hide file tree
Showing 7 changed files with 509 additions and 43 deletions.
145 changes: 102 additions & 43 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -427,43 +427,44 @@ import (
"fmt"
"log"

"github.com/nervosnetwork/ckb-sdk-go/indexer"
"github.com/nervosnetwork/ckb-sdk-go/rpc"
"github.com/nervosnetwork/ckb-sdk-go/types"
"github.com/nervosnetwork/ckb-sdk-go/utils"
"github.com/nervosnetwork/ckb-sdk-go/collector"
"github.com/nervosnetwork/ckb-sdk-go/indexer"
"github.com/nervosnetwork/ckb-sdk-go/rpc"
"github.com/nervosnetwork/ckb-sdk-go/types"
"github.com/nervosnetwork/ckb-sdk-go/utils"
)

func main() {
client, err := rpc.DialWithIndexer("http://localhost:8114", "http://localhost:8116")
if err != nil {
log.Fatalf("create rpc client error: %v", err)
}
}
args, _ := hex.DecodeString("edcda9513fa030ce4308e29245a22c022d0443bb")
searchKey := &indexer.SearchKey{
Script: &types.Script{
CodeHash: types.HexToHash("0x9bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce8"),
HashType: types.HashTypeType,
Args: args,
},
ScriptType: indexer.ScriptTypeLock,
}
processor := utils.NewCapacityLiveCellProcessor(10000000000000000)

// collect by type script
processor.EmptyData = false
processor.TypeScript = &types.Script{
CodeHash: types.HexToHash("0x48dbf59b4c7ee1547238021b4869bceedf4eea6b43772e5d66ef8865b6ae7212"),
HashType: types.HashTypeData,
Args: types.HexToHash("0x6a242b57227484e904b4e08ba96f19a623c367dcbd18675ec6f2a71a0ff4ec26").Bytes(),
searchKey := &indexer.SearchKey{
Script: &types.Script{
CodeHash: types.HexToHash("0x9bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce8"),
HashType: types.HashTypeType,
Args: args,
},
ScriptType: indexer.ScriptTypeLock,
}
c := collector.NewLiveCellCollector(client, searchKey, indexer.SearchOrderAsc, indexer.SearchLimit, "")
iterator, err := c.Iterator()
if err != nil {
log.Fatalf("collect cell error: %v", err)
}
var cells []*indexer.LiveCell
for iterator.HasNext() {
liveCell, err := iterator.CurrentItem()
if err != nil {
log.Fatalf("get cell error: %v", err)
}
cells = append(cells, liveCell)
err = iterator.Next()
if err != nil {
log.Fatalf("iterat error: %v", err)
}
}
collector := utils.NewLiveCellCollector(client, searchKey, indexer.SearchOrderAsc, 1000, "", processor)

// default collect null type script
fmt.Println(collector.Collect())

cells, err := collector.Collect()

fmt.Println(err)
fmt.Println(cells)
}
```
Expand All @@ -477,6 +478,7 @@ import (
"encoding/hex"
"fmt"
"github.com/ethereum/go-ethereum/common"
"github.com/nervosnetwork/ckb-sdk-go/collector"
"github.com/nervosnetwork/ckb-sdk-go/indexer"
"github.com/nervosnetwork/ckb-sdk-go/rpc"
"github.com/nervosnetwork/ckb-sdk-go/types"
Expand Down Expand Up @@ -509,24 +511,81 @@ func main() {
BlockRange: &[2]uint64{46843, 46844},
},
}
processor := utils.NewCapacityLiveCellProcessor(10000000000000000)

// collect by type script
processor.EmptyData = false
processor.TypeScript = &types.Script{
CodeHash: types.HexToHash("0x48dbf59b4c7ee1547238021b4869bceedf4eea6b43772e5d66ef8865b6ae7212"),
HashType: types.HashTypeData,
Args: types.HexToHash("0x6a242b57227484e904b4e08ba96f19a623c367dcbd18675ec6f2a71a0ff4ec26").Bytes(),
c := collector.NewLiveCellCollector(client, searchKey, indexer.SearchOrderAsc, indexer.SearchLimit, "")
iterator, err := c.Iterator()
if err != nil {
log.Fatalf("collect cell error: %v", err)
}
var cells []*indexer.LiveCell
for iterator.HasNext() {
liveCell, err := iterator.CurrentItem()
if err != nil {
log.Fatalf("get cell error: %v", err)
}
cells = append(cells, liveCell)
err = iterator.Next()
if err != nil {
log.Fatalf("iterat error: %v", err)
}
}
collector := utils.NewLiveCellCollector(client, searchKey, indexer.SearchOrderAsc, 1000, "", processor)
fmt.Println(cells)
}
```

// default collect null type script
fmt.Println(collector.Collect())
#### 5.2 Collect cells and filter out immature cells

cells, err := collector.Collect()
```go
package main

fmt.Println(err)
fmt.Println(cells)
import (
"context"
"encoding/hex"
"fmt"
"github.com/ethereum/go-ethereum/common"
"github.com/nervosnetwork/ckb-sdk-go/collector"
"github.com/nervosnetwork/ckb-sdk-go/indexer"
"github.com/nervosnetwork/ckb-sdk-go/rpc"
"github.com/nervosnetwork/ckb-sdk-go/types"
"github.com/nervosnetwork/ckb-sdk-go/utils"
"log"
)

func main() {
client, err := rpc.DialWithIndexer("http://localhost:8114", "http://localhost:8116")
if err != nil {
log.Fatalf("create rpc client error: %v", err)
}
args, _ := hex.DecodeString("edcda9513fa030ce4308e29245a22c022d0443bb")
maxMatureBlockNumber, err := utils.GetMaxMatureBlockNumber(client, context.Background())
searchKey := &indexer.SearchKey{
Script: &types.Script{
CodeHash: types.HexToHash("0x9bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce8"),
HashType: types.HashTypeType,
Args: args,
},
ScriptType: indexer.ScriptTypeLock,
}
c := collector.NewLiveCellCollector(client, searchKey, indexer.SearchOrderAsc, indexer.SearchLimit, "")
iterator, err := c.Iterator()
if err != nil {
log.Fatalf("collect cell error: %v", err)
}
var cells []*indexer.LiveCell
for iterator.HasNext() {
liveCell, err := iterator.CurrentItem()
if err != nil {
log.Fatalf("get cell error: %v", err)
}
if utils.IsMature(liveCell, maxMatureBlockNumber) {
cells = append(cells, liveCell)
}

err = iterator.Next()
if err != nil {
log.Fatalf("iterat error: %v", err)
}
}
fmt.Println(len(cells))
}
```

Expand Down
23 changes: 23 additions & 0 deletions mocks/Client.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 11 additions & 0 deletions rpc/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,8 @@ type Client interface {
// GetBlockByNumber get block by number
GetBlockByNumber(ctx context.Context, number uint64) (*types.Block, error)

GetConsensus(ctx context.Context) (*types.Consensus, error)

////// Experiment
// DryRunTransaction dry run transaction and return the execution cycles.
// This method will not check the transaction validity,
Expand Down Expand Up @@ -381,6 +383,15 @@ func (cli *client) EstimateFeeRate(ctx context.Context, blocks uint64) (*types.E
}, err
}

func (cli *client) GetConsensus(ctx context.Context) (*types.Consensus, error) {
var result consensus
err := cli.c.CallContext(ctx, &result, "get_consensus")
if err != nil {
return nil, nil
}
return toConsensus(result), nil
}

func (cli *client) IndexLockHash(ctx context.Context, lockHash types.Hash, indexFrom uint64) (*types.LockHashIndexState, error) {
var result lockHashIndexState

Expand Down
70 changes: 70 additions & 0 deletions rpc/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,40 @@ type minerReward struct {
Proposal hexutil.Big `json:"proposal"`
}

type rationalU256 struct {
Denom hexutil.Big `json:"denom"`
Numer hexutil.Big `json:"numer"`
}

type proposalWindow struct {
Closest hexutil.Uint64 `json:"closest"`
Farthest hexutil.Uint64 `json:"farthest"`
}

type consensus struct {
Id string `json:"ID"`
GenesisHash types.Hash `json:"genesis_hash"`
DaoTypeHash types.Hash `json:"dao_type_hash"`
Secp256k1Blake160SighashAllTypeHash types.Hash `json:"secp256k1_blake160_sighash_all_type_hash"`
Secp256k1Blake160MultisigAllTypeHash types.Hash `json:"secp256k1_blake160_multisig_all_type_hash"`
InitialPrimaryEpochReward hexutil.Uint64 `json:"initial_primary_epoch_reward"`
SecondaryEpochReward hexutil.Uint64 `json:"secondary_epoch_reward"`
MaxUnclesNum hexutil.Uint64 `json:"max_uncles_num"`
OrphanRateTarget rationalU256 `json:"orphan_rate_target"`
EpochDurationTarget hexutil.Uint64 `json:"epoch_duration_target"`
TxProposalWindow proposalWindow `json:"tx_proposal_window"`
ProposerRewardRatio rationalU256 `json:"proposer_reward_ratio"`
CellbaseMaturity hexutil.Uint64 `json:"cellbase_maturity"`
MedianTimeBlockCount hexutil.Uint64 `json:"median_time_block_count"`
MaxBlockCycles hexutil.Uint64 `json:"max_block_cycles"`
BlockVersion hexutil.Uint `json:"block_version"`
TxVersion hexutil.Uint `json:"tx_version"`
TypeIdCodeHash types.Hash `json:"type_id_code_hash"`
MaxBlockProposalsLimit hexutil.Uint64 `json:"max_block_proposals_limit"`
PrimaryEpochRewardHalvingInterval hexutil.Uint64 `json:"primary_epoch_reward_halving_interval"`
PermanentDifficultyInDummy bool `json:"permanent_difficulty_in_dummy"`
}

func toHeader(head header) *types.Header {
return &types.Header{
CompactTarget: uint(head.CompactTarget),
Expand Down Expand Up @@ -499,3 +533,39 @@ func toNode(result node) *types.Node {
}
return ret
}

func toConsensus(c consensus) *types.Consensus {
result := &types.Consensus{
Id: c.Id,
GenesisHash: c.GenesisHash,
DaoTypeHash: c.DaoTypeHash,
Secp256k1Blake160SighashAllTypeHash: c.Secp256k1Blake160SighashAllTypeHash,
Secp256k1Blake160MultisigAllTypeHash: c.Secp256k1Blake160MultisigAllTypeHash,
InitialPrimaryEpochReward: uint64(c.InitialPrimaryEpochReward),
SecondaryEpochReward: uint64(c.SecondaryEpochReward),
MaxUnclesNum: uint64(c.MaxUnclesNum),
OrphanRateTarget: types.RationalU256{
Denom: (*big.Int)(&c.OrphanRateTarget.Denom),
Numer: (*big.Int)(&c.OrphanRateTarget.Numer),
},
EpochDurationTarget: uint64(c.EpochDurationTarget),
TxProposalWindow: types.ProposalWindow{
Closest: uint64(c.TxProposalWindow.Closest),
Farthest: uint64(c.TxProposalWindow.Farthest),
},
ProposerRewardRatio: types.RationalU256{
Denom: (*big.Int)(&c.ProposerRewardRatio.Denom),
Numer: (*big.Int)(&c.ProposerRewardRatio.Numer),
},
CellbaseMaturity: uint64(c.CellbaseMaturity),
MedianTimeBlockCount: uint64(c.MedianTimeBlockCount),
MaxBlockCycles: uint64(c.MaxBlockCycles),
BlockVersion: uint(c.BlockVersion),
TxVersion: uint(c.TxVersion),
TypeIdCodeHash: c.TypeIdCodeHash,
MaxBlockProposalsLimit: uint64(c.MaxBlockProposalsLimit),
PrimaryEpochRewardHalvingInterval: uint64(c.PrimaryEpochRewardHalvingInterval),
PermanentDifficultyInDummy: c.PermanentDifficultyInDummy,
}
return result
}
34 changes: 34 additions & 0 deletions types/chain.go
Original file line number Diff line number Diff line change
Expand Up @@ -238,3 +238,37 @@ type MinerReward struct {
Committed *big.Int `json:"committed"`
Proposal *big.Int `json:"proposal"`
}

type RationalU256 struct {
Denom *big.Int `json:"denom"`
Numer *big.Int `json:"numer"`
}

type ProposalWindow struct {
Closest uint64 `json:"closest"`
Farthest uint64 `json:"farthest"`
}

type Consensus struct {
Id string `json:"ID"`
GenesisHash Hash `json:"genesis_hash"`
DaoTypeHash Hash `json:"dao_type_hash"`
Secp256k1Blake160SighashAllTypeHash Hash `json:"secp256k1_blake160_sighash_all_type_hash"`
Secp256k1Blake160MultisigAllTypeHash Hash `json:"secp256k1_blake160_multisig_all_type_hash"`
InitialPrimaryEpochReward uint64 `json:"initial_primary_epoch_reward"`
SecondaryEpochReward uint64 `json:"secondary_epoch_reward"`
MaxUnclesNum uint64 `json:"max_uncles_num"`
OrphanRateTarget RationalU256 `json:"orphan_rate_target"`
EpochDurationTarget uint64 `json:"epoch_duration_target"`
TxProposalWindow ProposalWindow `json:"tx_proposal_window"`
ProposerRewardRatio RationalU256 `json:"proposer_reward_ratio"`
CellbaseMaturity uint64 `json:"cellbase_maturity"`
MedianTimeBlockCount uint64 `json:"median_time_block_count"`
MaxBlockCycles uint64 `json:"max_block_cycles"`
BlockVersion uint `json:"block_version"`
TxVersion uint `json:"tx_version"`
TypeIdCodeHash Hash `json:"type_id_code_hash"`
MaxBlockProposalsLimit uint64 `json:"max_block_proposals_limit"`
PrimaryEpochRewardHalvingInterval uint64 `json:"primary_epoch_reward_halving_interval"`
PermanentDifficultyInDummy bool `json:"permanent_difficulty_in_dummy"`
}
Loading

0 comments on commit 4d76309

Please sign in to comment.