Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Input/Ordering Block Implementation #2055

Open
wants to merge 105 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
105 commits
Select commit Hold shift + click to select a range
10362c9
WeakBlockAlgos
kushti Aug 22, 2023
76e2f60
Merge branch 'v5.0.15' of github.com:ergoplatform/ergo into weak-blocks
kushti Sep 12, 2023
c5d30d3
WeakBlockInfo, WeakBlockMessageSpec
kushti Sep 18, 2023
5c2eb29
impl steps
kushti Sep 28, 2023
d378942
Merge branch 'v5.0.16' of github.com:ergoplatform/ergo into weak-blocks
kushti Oct 25, 2023
8843114
initial weak blocks structures and algos
kushti Oct 30, 2023
5c4f9c2
compact block like messaging
kushti Oct 31, 2023
0dbfeb0
before structures
kushti Nov 1, 2023
1a68d0e
skeleton of processing algo
kushti Nov 4, 2023
1040926
weak blocks => sub blocks
kushti Nov 7, 2023
636f3d8
more weak=>sub renaming
kushti Nov 7, 2023
6293421
returning download plan
kushti Nov 7, 2023
23a5db0
better comments and todos, formatting
kushti Nov 9, 2023
2c5cf3c
motivation started in EIP, data structures refined
kushti Nov 10, 2023
4189783
Merge branch 'master' of github.com:ergoplatform/ergo into weak-blocks
kushti Nov 28, 2023
4962218
pow, superblocks
kushti Dec 1, 2023
514e6fb
subblocks section finished
kushti Dec 2, 2023
564ad05
propagation text started, prevSubBlockId made optional (comp fails)
kushti Dec 6, 2023
346e1a7
commitment
kushti Dec 21, 2023
a068545
styling fixes
kushti Dec 28, 2023
c0709f2
key spaces for sub-blocks and sidechains
kushti Dec 29, 2023
85de7a4
eip update
kushti Jan 3, 2024
a248ccf
dag note, new subsections added
kushti Jan 4, 2024
0a9fd56
Merge branch 'master' of github.com:ergoplatform/ergo into weak-blocks
kushti Feb 12, 2024
93bc6bc
merging w. master, accounting for optional prevSubBlockId
kushti Feb 12, 2024
02056c2
Merge branch 'master' of github.com:ergoplatform/ergo into weak-blocks
kushti Jul 17, 2024
92baed0
input/ordering blocks intro
kushti Jul 19, 2024
54c9971
script execution ctx started
kushti Jul 20, 2024
73d76f2
extending subblocks info
kushti Jul 24, 2024
69adf58
Merge branch 'master' of github.com:ergoplatform/ergo into weak-blocks
kushti Jul 30, 2024
bed12e6
SubsPerBlock* improved comments in SubBlockAlgos
kushti Jul 30, 2024
01da1a0
BlockKind, distnguishing fn
kushti Aug 3, 2024
e448fb8
Merge branch 'master' of github.com:ergoplatform/ergo into weak-blocks
kushti Aug 5, 2024
3e9f4d1
blockKind()
kushti Aug 6, 2024
1a8aaeb
unused reportModifierIsInvalid removed
kushti Aug 7, 2024
184996e
ProgressInfo.empty, removing implicit ScorexEncoder
kushti Aug 7, 2024
8bc72cc
MessageSpecInitial / MessageSpecSubBlock
kushti Aug 12, 2024
4192c61
merkle proof added to SubBlockInfo, serializer updated, SubBlockMessa…
kushti Aug 14, 2024
a044955
batch merkle proof usage and serialization
kushti Aug 29, 2024
613fc58
Merge branch 'jni-dep' of github.com:ergoplatform/ergo into weak-blocks
kushti Aug 29, 2024
c382a38
processSubblock started
kushti Sep 3, 2024
15ca997
subblock height check
kushti Sep 3, 2024
222c850
SubBlockTransactionsRequestSpec, completing processSubblock stub
kushti Sep 4, 2024
e6ee392
SubBlockTransactionsSpec
kushti Sep 5, 2024
fb98a2e
subblocks p2p logic stub
kushti Sep 8, 2024
95fb95e
LocallyGeneratedSubBlock
kushti Sep 13, 2024
5f66580
subblock keys, CandidateGenerator simplification
kushti Sep 13, 2024
f118879
more simplification in CandidateGenerator
kushti Sep 13, 2024
e8bcdfa
bestSubblock() stub. createCandidate #1
kushti Sep 13, 2024
647b6db
initial version of best subblock selection
kushti Sep 18, 2024
e93d333
merging w. 5.0.23
kushti Sep 19, 2024
e0feb83
input/ordering block distintcion in mining logic #1, input block gene…
kushti Sep 19, 2024
9ebe5db
subblocks generation
kushti Oct 1, 2024
5e623b4
fixing delivery of sub-blocks to processing
kushti Oct 1, 2024
c9de516
input block pow validation
kushti Oct 10, 2024
b908142
completeOrderingBlock / completeInputBlock
kushti Oct 10, 2024
08c52d6
sendInputToNodeView stub (pre-refactoring)
kushti Oct 15, 2024
ac824a4
LocallyGeneratedInputBlock / LocallyGeneratedOrderingBlock
kushti Oct 16, 2024
4fc43c5
reworked LocallyGeneratedInputBlock signature
kushti Oct 18, 2024
ef02664
forum post
kushti Oct 30, 2024
4011aa5
removing subblock field from Candidate
kushti Oct 30, 2024
e9811ce
Merge branch 'master' of github.com:ergoplatform/ergo into weak-blocks
kushti Dec 10, 2024
c81839d
papers/subblocks folder
kushti Dec 10, 2024
319f7a6
forming SubBlockInfo, SubBlockTransactionsData moved to completeInput…
kushti Dec 10, 2024
cac7cd1
Merge branch 'master' of github.com:ergoplatform/ergo into weak-blocks
kushti Dec 23, 2024
caf9f3f
subblock -> inputblock
kushti Dec 23, 2024
87a91d5
input blocks data pruning
kushti Dec 24, 2024
8e9d526
forming prevInputBlockId
kushti Dec 24, 2024
139d770
improving linking logic and code
kushti Dec 24, 2024
afb4ef4
refs, motivation rework
kushti Dec 28, 2024
8ed3749
EIP rework #1
kushti Dec 30, 2024
70c57c2
Transactions Handling
kushti Jan 1, 2025
d16aa23
Transactions Handling
kushti Jan 3, 2025
8d8afa5
propagation wip1
kushti Jan 3, 2025
3752b30
incentivization section
kushti Jan 4, 2025
e15dcd0
EIP alpha version
kushti Jan 4, 2025
7aae74a
update notes
kushti Jan 6, 2025
5d059f7
transactions handling section updatte
kushti Jan 7, 2025
7dfd05e
transactions handling update
kushti Jan 8, 2025
c5814df
input-block related extension fields
kushti Jan 9, 2025
251d097
generateCandidate comments
kushti Jan 10, 2025
7fd69ec
createCandidate refatoring
kushti Jan 10, 2025
b77765c
new extension fields stub
kushti Jan 10, 2025
7dcec20
forming prev input block id
kushti Jan 13, 2025
e34a181
comments for extension fields
kushti Jan 13, 2025
5773c17
reordering code before reworking forming transactions
kushti Jan 14, 2025
41f2d59
initial input/ordering txs split
kushti Jan 14, 2025
2245808
comments fix
kushti Jan 16, 2025
a4d892a
bestBlocks
kushti Jan 16, 2025
4633a5e
parentInputBlockIdOpt fix
kushti Jan 16, 2025
cebf363
transactionsCache
kushti Jan 16, 2025
8a4b690
input block id, prev link fix, accumulating ordering block transactions
kushti Jan 17, 2025
f687ca4
using previous ordering block transactions in orderingBlocktransactio…
kushti Jan 20, 2025
d0f7ca6
fixing subblocksPerBlock in checkNonces
kushti Jan 20, 2025
3288e61
checkInputBlockPoW & checkOrderingBlockPoW in AutolykosPowScheme
kushti Jan 20, 2025
879b50b
passing link to previous input block, clearing miner cache on input b…
kushti Jan 21, 2025
b689299
filtering out non-input transactions
kushti Jan 22, 2025
c77d30b
filtering out already included before collectTxs, id arg fix in apply…
kushti Jan 23, 2025
cac0278
real Merkle tree digests
kushti Jan 23, 2025
bca36db
NewBestInputBlock signal, /info field
kushti Jan 24, 2025
4988a6e
getInputBlock
kushti Jan 24, 2025
1aaa562
improving comments
kushti Jan 25, 2025
377d6c9
inputBlockParents stub
kushti Jan 27, 2025
c01a3d1
getBestInputBlocksChain
kushti Jan 27, 2025
9521425
bestInputBlock / bestInputChain
kushti Jan 28, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
223 changes: 223 additions & 0 deletions ergo-core/src/main/scala/org/ergoplatform/SubBlockAlgos.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,223 @@
package org.ergoplatform

import org.ergoplatform.mining.AutolykosPowScheme
import org.ergoplatform.modifiers.history.header.Header
import org.ergoplatform.network.message.MessageConstants.MessageCode
import org.ergoplatform.network.message.MessageSpecInitial
import org.ergoplatform.settings.{Constants, Parameters}
import org.ergoplatform.subblocks.InputBlockInfo
import scorex.util.Extensions._
import scorex.util.serialization.{Reader, Writer}
import scorex.util.{ModifierId, bytesToId, idToBytes}

import scala.collection.mutable

/**
* Implementation steps:
* * implement basic input block algorithms (isInput etc)
* * implement input block network message
* * implement input block info support in sync tracker
* * implement downloading input blocks chain
* * implement avoiding downloading full-blocks
* * input blocks support in /mining API
* * sub confirmations API
*/
object SubBlockAlgos {

// Only sub-blocks may have transactions, full-blocks may only bring block reward transaction ( designated
// by using emission or re-emission NFTs).
// As a full-block is also a sub-block, and miner does not know output in advance, the following requirements
// for the block are introduced. And to be on par with other proposals in consensus performance, we call them
// input block (sub-block) and ordering block(full-block):
// * ordering block's Merkle tree is corresponding to latest input block's Merkle tree , or latest ordering block's
// Merkle tree if there are no input blocks after previous ordering block, with only reward transaction added
// * every block (input and ordering) also contains digest of new transactions since last input block. For ordering
// block, they are ignored.
// * script execution context different for input and ordering blocks for the following fields :
// * timestamp - next input or ordering block has non-decreasing timestamp to ours
// * height - the same for input blocks and next ordering block
// * votes - could be different in different (input and ordering) blocks
// * minerPk - could be different in different (input and ordering) blocks

// Another option is to use 2-PoW-for 1 technique, so sub-block (input block) is defined not by
// hash(b) < T/subsPerBlock , but by reverse(hash(b)) < T/subsPerBlock , while ordering block is defined
// by hash(b) < T

// sub blocks per block, adjustable via miners voting
// todo: likely we need to update rule exMatchParameters (#409) to add new parameter to vote
val subsPerBlock = Parameters.SubsPerBlockDefault

val weakTransactionIdLength = 6 // value taken from Bitcoin's compact blocks BIP

lazy val powScheme = new AutolykosPowScheme(32, 26)

sealed trait BlockKind

case object InputBlock extends BlockKind
case object OrderingBlock extends BlockKind
case object InvalidPoWBlock extends BlockKind

def blockKind(header: Header): BlockKind = {
val fullTarget = powScheme.getB(header.nBits)
val subTarget = fullTarget * subsPerBlock
val hit = powScheme.hitForVersion2(header) // todo: cache hit in header

// todo: consider 2-for-1 pow technique
if (hit < subTarget) {
InputBlock
} else if (hit >= subTarget && hit < fullTarget) {
OrderingBlock
} else {
InvalidPoWBlock
}
}

// messages:
//
// sub block signal:
// version
// sub block (~200 bytes) - contains a link to parent block
// previous sub block id
// transactions since last sub blocks



/**
* On receiving sub block or block, the node is sending last sub block or block id it has to get short transaction
* ids since then
*/
object GetDataSpec extends MessageSpecInitial[ModifierId] {

import scorex.util.{bytesToId, idToBytes}

override val messageCode: MessageCode = 91: Byte
override val messageName: String = "GetData"

override def serialize(data: ModifierId, w: Writer): Unit = {
w.putBytes(idToBytes(data))
}

override def parse(r: Reader): ModifierId = {
bytesToId(r.getBytes(Constants.ModifierIdSize))
}
}

case class TransactionsSince(transactionsWithBlockIds: Array[(ModifierId, Array[Array[Byte]])])

class DataSpec extends MessageSpecInitial[TransactionsSince] {

override val messageCode: MessageCode = 92: Byte
override val messageName: String = "GetData"

override def serialize(data: TransactionsSince, w: Writer): Unit = {
w.putUInt(data.transactionsWithBlockIds.length)
data.transactionsWithBlockIds.foreach { case (id, txIds) =>
w.putBytes(idToBytes(id))
w.putUInt(txIds.length)
txIds.foreach { txId =>
w.putBytes(txId)
}
}
}

override def parse(r: Reader): TransactionsSince = {
val blocksCount = r.getUInt().toIntExact
val records = (1 to blocksCount).map { _ =>
val blockId = r.getBytes(32)
val txsCount = r.getUInt().toIntExact
val txIds = (1 to txsCount).map { _ =>
r.getBytes(6)
}.toArray
bytesToId(blockId) -> txIds
}.toArray
TransactionsSince(records)
}
}

}

object structures {
var lastBlock: Header = null // we ignore forks for now

// all the sub-blocks known since the last block
val subBlocks: mutable.Map[ModifierId, Header] = mutable.Map.empty

// links from sub-blocks to their parent sub-blocks
val subBlockLinks: mutable.Map[ModifierId, ModifierId] = mutable.Map.empty

// only new transactions appeared in a sub-block
var subBlockTxs: Map[ModifierId, Array[Array[Byte]]] = Map.empty


/**
* A primer algo on processing sub-blocks in p2p layer. It is updating internal sub-block related
* caches and decides what to download next
*
* @param sbi
* @return - sub-block ids to download, sub-block transactions to download
*/
def processSubBlock(sbi: InputBlockInfo): (Seq[ModifierId], Seq[ModifierId]) = {
val sbHeader = sbi.header
val prevSbIdOpt = sbi.prevInputBlockId.map(bytesToId)
val sbHeight = sbHeader.height

def emptyResult: (Seq[ModifierId], Seq[ModifierId]) = Seq.empty -> Seq.empty

prevSbIdOpt match {
case None => ??? // todo: link to prev block

case Some(prevSbId) =>
if (sbHeader.id == prevSbId) {
??? // todo: malicious prev throw error
}

if (sbHeight < lastBlock.height + 1) {
// just ignore as we have better block already
emptyResult
} else if (sbHeight == lastBlock.height + 1) {
if (sbHeader.parentId == lastBlock.id) {
val subBlockId = sbHeader.id
if (subBlocks.contains(subBlockId)) {
// we got sub-block we already have
// todo: check if previous sub-block and transactions are downloaded
emptyResult
} else {
subBlocks += subBlockId -> sbHeader
if (subBlocks.contains(prevSbId)) {
val prevSb = subBlocks(prevSbId)
subBlockLinks.put(subBlockId, prevSbId)
if (prevSb.transactionsRoot != sbHeader.transactionsRoot) {
(Seq.empty, Seq(sbHeader.id))
} else {
emptyResult // no new transactions
}
} else {
//todo: download prev sub block id
(Seq(prevSbId), Seq(sbHeader.id))
}
// todo: download sub block related txs
}
} else {
// todo: we got orphaned block's sub block, do nothing for now, but we need to check the block is downloaded
emptyResult
}
} else {
// just ignoring sub block coming from future for now
emptyResult
}
}
}

def processBlock(header: Header): Unit = {
if (header.height > lastBlock.height) {
lastBlock = header
subBlocks.clear()
subBlockLinks.clear()
subBlockTxs = Map.empty
} else {
??? // todo: process
}
}

}

Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,19 @@ import scorex.util.ModifierId
case class ProgressInfo[PM <: BlockSection](branchPoint: Option[ModifierId],
toRemove: Seq[PM],
toApply: Seq[PM],
toDownload: Seq[(NetworkObjectTypeId.Value, ModifierId)])
(implicit encoder: ScorexEncoder) {
toDownload: Seq[(NetworkObjectTypeId.Value, ModifierId)]) {

if (toRemove.nonEmpty)
require(branchPoint.isDefined, s"Branch point should be defined for non-empty `toRemove`")

lazy val chainSwitchingNeeded: Boolean = toRemove.nonEmpty

override def toString: String = {
s"ProgressInfo(BranchPoint: ${branchPoint.map(encoder.encodeId)}, " +
s"ProgressInfo(BranchPoint: ${branchPoint.map(ScorexEncoder.encodeId)}, " +
s" to remove: ${toRemove.map(_.encodedId)}, to apply: ${toApply.map(_.encodedId)})"
}
}

object ProgressInfo {
val empty = ProgressInfo[BlockSection](None, Seq.empty, Seq.empty, Seq.empty)
}
8 changes: 4 additions & 4 deletions ergo-core/src/main/scala/org/ergoplatform/core/core.scala
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,18 @@ package object core {

type VersionTag = VersionTag.Type

def idsToString(ids: Seq[(NetworkObjectTypeId.Value, util.ModifierId)])(implicit enc: ScorexEncoder): String = {
def idsToString(ids: Seq[(NetworkObjectTypeId.Value, util.ModifierId)]): String = {
List(ids.headOption, ids.lastOption)
.flatten
.map { case (typeId, id) => s"($typeId,${enc.encodeId(id)})" }
.map { case (typeId, id) => s"($typeId,${ScorexEncoder.encodeId(id)})" }
.mkString("[", "..", "]")
}

def idsToString(modifierType: NetworkObjectTypeId.Value, ids: Seq[util.ModifierId])(implicit encoder: ScorexEncoder): String = {
def idsToString(modifierType: NetworkObjectTypeId.Value, ids: Seq[util.ModifierId]): String = {
idsToString(ids.map(id => (modifierType, id)))
}

def idsToString(invData: InvData)(implicit encoder: ScorexEncoder): String = idsToString(invData.typeId, invData.ids)
def idsToString(invData: InvData): String = idsToString(invData.typeId, invData.ids)

def bytesToId: Array[Byte] => util.ModifierId = scorex.util.bytesToId

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package org.ergoplatform.http.api

import cats.syntax.either._
import io.circe._
import cats.syntax.either._ // needed for Scala 2.11
import io.circe._ // needed for Scala 2.11
import io.circe.syntax._
import org.bouncycastle.util.BigIntegers
import org.ergoplatform.ErgoBox.RegisterId
Expand Down
Loading
Loading