current position:Home>Accessing blockchain data from scrypt smart contract (2)
Accessing blockchain data from scrypt smart contract (2)
2022-02-02 10:49:01 【freedomhero】
stay Last article in , We introduce a method of accessing blocks and transactions with minimal trust .
In this paper , We extend it to include multiple blocks . Use the technology , We developed a simple betting contract based on block time . We also show another way to prevent forged blocks .
A sequence of blocks
As shown below ,isBlockHeaderValid()
Validate a block sequence , Instead of the single block we did in the last article . We are the first 8
Line reuses functions in existing code isBlockHeaderValid()
To verify each individual block . Besides , We are the first 12
The row hashes the block header , And make sure that the hash is the same as 14
In the next block header of the line prevBlockHash
Field matching .
// is a chain of block headers valid
static function isBlockHeaderChainValid(static const int N, BlockHeader[N] headers, int blockchainTarget) : bool {
bool res = true;
loop (N) : i {
if (res) {
// each block is valid
if (!isBlockHeaderValid(headers[i], blockchainTarget))
res = false;
if (i > 0) {
Sha256 prevBlockHash = blockHeaderHash(headers[i - 1]);
// blocks are chained
if (prevBlockHash != headers[i].prevBlockHash)
res = false;
}
}
}
return res;
}
in other words , Verify that the two blocks are linked together .
A case study : Bet on the block time
On average, , Generating a block on bitcoin requires 10 minute .Alice and Bob Want to bet on how long it will take to dig a particular block . Each of them has locked in some... In a transaction that includes the following smart contracts BSV. After the transaction broadcast , Package the process into a block . If the generation time of the block is less than 10
minute , be Alice Win and take all locked BSV; otherwise , Bob won . We use the timestamp of the block ( The... In the header 4 A field ) The difference between the timestamp of its previous block is taken as the out of block time ¹.
// bet on block time: how long it takes to mine the block containing the bet transaction
contract BlockTimeBet {
// only 2 is needed; 7 means the transaction has 6 confirmations
static const int N = 7;
// 10 minutes in seconds
static const int AVG_BLOCK_TIME = 600;
// maximal target for any block to be considered valid
int blockchainTarget;
PubKey alice;
PubKey bob;
// header[1] is the block containing the contract tx
public function main(BlockHeader[N] headers, MerkleProof merkleproof, Sig sig, SigHashPreimage txPreimage) {
require(Tx.checkPreimage(txPreimage));
// get id of previous tx
Sha256 prevTxid = Sha256(SigHash.outpoint(txPreimage)[:32]);
// validate a chain of block headers
require(Blockchain.isBlockHeaderChainValid(N, headers, this.blockchainTarget));
// verify previous tx is in block with index 1
require(Blockchain.txInBlock(prevTxid, headers[1], merkleproof));
// block time is the time difference between this block and last
int blockTime = headers[1].time - headers[0].time;
// Alice wins if block is mined within 10 mins; otherwise Bob wins
PubKey winner = blockTime < AVG_BLOCK_TIME ? this.alice : this.bob;
require(checkSig(sig, winner));
}
}
Similar to the previous article BlockchainPRNG The contract is the same , We use OP_PUSH_TX technology To get the information of the transaction containing the betting contract txid
. The first 20
Line to verify whether the block header chain is legal , The first 23
The bank verifies that the betting transaction is in it . The first 26
The block time is calculated from the row , Used in 29
OK, determine the winner .
Identify false blocks
In the last article , We introduced blockchainTarget
Parameters to control the difficulty of acceptable block headers . We can also ask to build multiple blocks on top of one block , This makes it more difficult to import fake block data . The more blocks required , The higher the cost of counterfeiting it . This is similar to what you need to buy goods with bitcoin 6
Second confirmation . In the betting contract above , We just need to put N Change it to 7
This ensures that the transaction containing the contract has 6
Confirmations .
appendix
[1]: Bitcoin block timestamp is not accurate , Usually cannot be used to measure 10
A minute interval . But as long as it's random and unpredictable , Just bet on the contract , Because it depends on the randomness of block time , Not its accuracy .
copyright notice
author[freedomhero],Please bring the original link to reprint, thank you.
https://en.netfreeman.com/2022/02/202202021048586562.html
The sidebar is recommended
- CEO of DeVere group: Ethereum's rise as the largest cryptocurrency "seems unstoppable"
- The Vienna Stock Exchange will list the encrypted ETP of London financial services company etc group
- Analysts said Ethereum's "liquidity crisis" could set an all-time high ahead of bitcoin
- Compound's general counsel: the U.S. Treasury hopes to "capture defi" through the infrastructure bill
- After six years of silence, the dog coin foundation will be officially rebuilt
- Analysts say $46500 is a key level for bitcoin to regain support
- Alex Saunders was attacked again after Nuggets news failed to start its virtual headquarters in decentraland
- Tiktok cooperates with audius, a cryptocurrency based music streaming platform
- Cointegraph Chinese news platform app officially launched
- The five most noteworthy cryptocurrencies this week: BTC, etc, Luna, Klay and AXS
guess what you like
-
US Treasury to help? Its officials will clarify the encrypted tax reporting rules in the infrastructure bill
-
Fitch Ratings warned that El Salvador's "bitcoin law" will bring risks to local insurance companies
-
How is the defi protocol attacked by hackers?
-
Qucoin morning post | Ibox issued classic traditional Chinese painting, which was sold out immediately after NFT went online
-
Metamask: it has not been acquired by financial institutions and has never communicated with JPMorgan Chase
-
Advisor shares submits an application for active management bitcoin ETF to the sec
-
Why is the meta universe the "beautiful new world" of the next generation Internet
-
Kusama is about to enter the second round of auction. How far is Polkadot's auction?
-
Immutable X and Gala games who are more likely to become chain game steam?
-
Coinbase interview with Mina CEO: ZK snarks is encryption magic
Random recommended
- Why is it an inevitable trend for blockchain to integrate privacy computing?
- Hitbtc: mnemonic word leakage is sentinel software vulnerability. Sentinel is shirking technical defects
- POS who often changes new clothes
- In the wave of gamefi, who can win this infrastructure card battle?
- Coinbase interview with Mina CEO: Justin said ZK snarks is encryption magic
- Project weekly V God: I hope Ethereum can run the meta universe in 5-10 years
- The total lock up volume of Qu coin defi daily | defi agreement exceeded US $110 billion
- The story behind horizen labs's $7 million seed round financing
- Decoding: NFT and CBDC collide with the future of finance. Does the United States have corresponding encryption regulations?
- Technical weekly Ethereum 2.0 test network Pyrmont completes Altair hard bifurcation
- Will globalization be the future outlet of bitcoin mining enterprises?
- What does "tiktok + blockchain" mean in the music industry?
- Will NFT break the circle be a new dawn in the encryption industry?
- Why is it an inevitable trend for blockchain to integrate privacy computing?
- POS who often changes new clothes
- Qu coin Morning Post predicts that the Federal Reserve will eventually issue its own digital currency
- In depth analysis of the sustainability of gamefi chain games from the underlying technology and business logic
- Master the necessary resources and analysis tools of NFT
- Source: 10t holdings and akuna capital purchased US $100 million equity of derivative trading platform deribit in the secondary market
- Ethereum core developer: Ethereum difficulty bomb may be postponed again
- DAPP industry overview in July: the heat is rising, with about 1.4 million independent users every day
- How do I integrate cefi and defi with Solana?
- Global cryptocurrency adoption index in 2021: conversion between economic powers and emerging markets
- Experience of NFT exchange element
- New infrastructure of Web 3.0 adds a strong general: is cloud computing platform a positive solution?
- Experience of NFT exchange element
- How do I integrate cefi and defi with Solana?
- Master the necessary resources and analysis tools of NFT
- Global cryptocurrency adoption index in 2021: conversion between economic powers and emerging markets
- Next week, the near ecological action will be frequent, and Terra's "columbus-5 upgrade" governance vote will end
- Why on earth is crazy stone? Understand the value of "money is caprice"
- Defi weekly sec Chairman: no matter how "decentralized", defi must be regulated
- Defi era: how does Dao Treasury manage assets
- What are the differences between the most popular synthetic asset platforms
- Federal Reserve: the issuance of CBDC will make usdt and other stable currencies disappear
- NFT trading volume breaks record, quick view of potential projects and exploration Guide
- Shapeshift, Daos and the future of work
- Hard core observation 371 bitcoin BSV miners dig 2GB blocks on the blockchain
- Zhanrui and its partners released: the world's first PSA certified software and hardware integrated IOT blockchain solution
- Blockchain card game NFT game development