scieee AI-readable full text Open interactive document viewer

Blockchain meets Alloy

Araújo, Diogo João Silva de

Abstract

Blockchain technology has gained enormous importance in real world due to its application to many sys tems. Cryptocurrencies (e.g. Bitcoin and Ethereum) use Blockchain to ensure system security and relia bility. The use of formal methods, namely formal verification, in the blockchain domain is not main stream, let alone the use of model checking techniques. This project aims at filling such a gap by undertaking a comprehensive study of blockchain components, trying to identify some generic patterns and modeling such a protocol through formal specifications. Throughout this dissertation, the Alloy model checker will conduct the modeling process, emphasizing scenarios that do not correctly describe blockchain technology. Such inconsistencies are tackled using a relational approach to push constraints on the model in order to stepwisely reach an adequate formal description of the blockchain protocol. The work starts by introducing the Formal Methods in Blockchain (FMBC) area of research and pre senting the motivation and objectives of the project. The literature on blockchain and cryptocurrencies is then subject to a state-of-the-art review. Next, the Alloy tool will guide the process of specifying blockchain (and bitcoin) principles leading to the development of a model that represents the blockchain technology in a comprehensive and adequate way. Finally, some conclusions are drawn and a prospect of future work is given.

Full text

University of Minho School of Engineering Diogo João Silva de Araújo Blockchain meets Alloy January 2024 University of Minho School of Engineering Diogo João Silva de Araújo Blockchain meets Alloy Master’s Dissertation in Informatics Engineering Dissertation supervised by José N. Oliveira January 2024 Copyright and Terms of Use for Third Party Work This dissertation reports on academic work that can be used by third parties as long as the internationally accepted standards and good practices are respected concerning copyright and related rights. This work can thereafter be used under the terms established in the license below. Readers needing authorization conditions not provided for in the indicated licensing should contact the author through the RepositóriUM of the University of Minho. License granted to users of this work: CC BY https://creativecommons.org/licenses/by/4.0/ i Acknowledgements At the commencement of this dissertation, I extend my deepest gratitude to my advisor, José Nuno Oliveira, for his exceptional guidance and unwavering support throughout the entirety of this project. His expertise, mentorship, and insightful advice have been instrumental in shaping the trajectory of my research. José Nuno Oliveira’s dedication to the supervision of this work, coupled with his commitment to steering me in the right direction, has significantly contributed to the success of this academic endeavor. His continuous encouragement, intellectual guidance, and scholarly insights have been invaluable, providing a solid foundation upon which this dissertation has been built. In addition to expressing my profound appreciation to my advisor, I extend heartfelt thanks to my father José Araújo, my mother Maria Paula Silva, my brother Afonso Araújo, and my circle of friends. Their unwavering support and encouragement have played a pivotal role in this academic journey. This dissertation is a testament to the collaborative efforts and guidance received from those who have contributed to my academic and personal growth. I am sincerely grateful for the mentorship and support that have enriched this transformative experience. ii Statement of Integrity I hereby declare having conducted this academic work with integrity. I confirm that I have not used plagiarism or any form of undue use of information or falsification of results along the process leading to its elaboration. I further declare that I have fully acknowledged the Code of Ethical Conduct of the University of Minho. Diogo João Silva de Araújo iii Abstract Blockchain technology has gained enormous importance in real world due to its application to many systems. Cryptocurrencies (e.g. Bitcoin and Ethereum) use Blockchain to ensure system security and reliability. The use of formal methods, namely formal verification, in the blockchain domain is not main stream, let alone the use of model checking techniques. This project aims at filling such a gap by undertaking a comprehensive study of blockchain components, trying to identify some generic patterns and modeling such a protocol through formal specifications. Throughout this dissertation, the Alloy model checker will conduct the modeling process, emphasizing scenarios that do not correctly describe blockchain technology. Such inconsistencies are tackled using a relational approach to push constraints on the model in order to stepwisely reach an adequate formal description of the blockchain protocol. The work starts by introducing the Formal Methods in Blockchain (FMBC) area of research and presenting the motivation and objectives of the project. The literature on blockchain and cryptocurrencies is then subject to a state-of-the-art review. Next, the Alloy tool will guide the process of specifying blockchain (and bitcoin) principles leading to the development of a model that represents the blockchain technology in a comprehensive and adequate way. Finally, some conclusions are drawn and a prospect of future work is given. Keywords Blockchain, Bitcoin, Formal Methods, Formal Verification, Model Checking, Alloy iv Resumo A tecnologia Blockchain tem vindo a ganhar enorme importância no mundo atual devido à sua aplicação em diversos sistemas. Criptomoedas como Bitcoin e Ethereum utilizam Blockchain para conferir segurança e confiança aos respectivos sistemas. A utilização de métodos formais, nomeadamente a verificação formal, no domínio da Blockchain não é uma prática corrente, muito menos a utilização de técnicas de verificação de modelos. Este projeto pretende colmatar essa lacuna através de um estudo exaustivo dos componentes da blockchain, tentando identificar alguns padrões genéricos e modelar esse protocolo através de especificações formais. Ao longo desta dissertação, a ferramenta de verificação Alloy conduzirá o processo de modelação, detetando cenários que possam descrever incorretamente a tecnologia blockchain. Tais inconsistências serão tratadas utilizando uma abordagem relacional para impor restrições ao modelo, de forma a desenvolver um protocolo fiável tal como descrito no blockchain. O trabalho começa por introduzir a área de investigação de Métodos Formais em Blockchain (FMBC) e apresentar a motivação e objetivos do projeto. A literatura sobre blockchain e criptomoedas (em especial o bitcoin) é então objeto de uma revisão. De seguida, a ferramenta Alloy guia o processo de especificação do blockchain (e do bitcoin), conduzindo ao desenvolvimento de um modelo que representa a tecnologia blockchain de forma completa e adequada. Por último, são apresentadas as conclusões, bem como pistas para trabalho futuro. Palavras-chave Blockchain, Bitcoin, Métodos Formais, Verificação Formal, Validação de Modelo, Alloy v Contents 1 Introduction 1 1.1 Context ........................................ 1 1.2 Motivation and Goals ................................. 2 1.3 Dissertation Structure ................................. 3 2 State of the Art 5 2.1 Preliminary analysis of the bibliography ........................ 5 2.2 Alloy Overview .................................... 6 2.3 Understanding Blockchain Basics ........................... 13 2.3.1 What is a Blockchain ............................. 13 2.3.2 Understanding SHA-256 ........................... 14 2.3.3 Immutable Ledger .............................. 15 2.3.4 Distributed P2P Network ........................... 16 2.3.5 How Mining Works .............................. 17 2.3.6 Consensus Protocol ............................. 19 2.3.7 Merkle Trees ................................. 21 2.4 Cryptocurrencies ................................... 22 2.4.1 What is Bitcoin ................................ 22 2.4.2 Bitcoin’s Monetary Policy ........................... 23 2.4.3 Understanding Mining Difficulty ........................ 24 2.4.4 Mining Pools ................................. 25 2.4.5 Nonce Range ................................. 25 2.4.6 How Miners Pick Transactions ........................ 26 2.4.7 How Do Mempools work ........................... 27 2.4.8 Orphaned Blocks ............................... 27 vi Blockchain with criptography first appeared in 1991 in the work of Stuart Haber and W. Scott Stornetta (Haber and Stornetta,1991). The main aim of this promising infrastructural technology with potential to be leveraged in different aspects of cybersecurity is to guarantee authenticity, reliability and integrity of data based on characteristics such as decentralization, verifiability and immutability (Parizi et al.,2020). Blockchain has been gaining popularity in recent years and it is used in several systems such as cryptocurrencies. Nowadays, this system is getting the interest of banks, companies and government organizations. This is because the correct operation of systems can be based on Blockchain principles. Therefore, it is of utmost importance to guarantee Blockchain is a reliable technology. Ensuring correct behavior can be brought by using techniques based on mathematical formalisms for software system verification, leading to the relatively recent research area of formal methods for blockchain (FMBC). Applying formal verification and model checking to blockchain software design using Alloy (Jackson,2012) is the main topic of the research that is described in this dissertation. Blockchain has a wide range of applications. For example, Proofgold is a cryptocurrency network with support for formal logic and mathematics. Users can publish theories and then develop a theory by publishing documents with definitions, conjectures and proofs. The theories and their state of development is recorded by Blockchain to ensure security (Brown et al.,2022). Most major advances in software technology were driven by formal techniques underpinning such developments. For example, the theory of finite-state automata underlies compiler construction; cryptography underlies security, and so on. Formal methods include so-called light-weight techniques that, even if not ensuring total correctness, help a lot in making software more reliable. Model checking in Alloy is one such technique, as it can help to identify and detect inconsistencies, conflicts or undesirable scenarios that can be corrected by introducing rules and restrictions in the form of invariant properties. Formalizing blockchain components with the help of the Alloy tool may be a turning point paving the way to the design of well-formed, type-safe, and faultless blockchains. 1.2 Motivation and Goals With the advent and increasing popularity of cryptocurrencies such as Bitcoin and Ethereum, it is of utmost importance to have strong behaviour guarantees of the blockchain software they rely upon. Ensuring correct behavior can be brought by using formal methods (FM) and, indeed, there is a series of workshops devoted to formal methods applied to blockchain software.1Particular techniques such as 1Namely: FMBC’19,FMBC’20,FMBC’21 and FMBC’22. 2 theorem proving and formal semantics have been successfully applied to blockchain, for instance. However, there seems to be no reported experience in formal verification, namely model checking using Alloy model checker (Jackson,2012), in this domain. The main aim of this project is to challenge such verification, validation methods in the blockchain arena and to see how they compare to the other formal approaches. Formal methods for blockchain (FMBC) is a relatively new research subject. The first FMBC workshop took place in October 2019, as part of the 3rd World Congress in Formal Methods (Sekerinski and et al ,2020). This inaugurated a series of events which aim at ensuring safety and quality in blockchain technologies by use of formal method techniques (see footnote 1). These have included theorem proving over formal semantics definition (e.g. Gabbay et al. (2021)) but not model checking advocated by the formal verification (e.g. Oliveira and Ferreira (2013)) and supported by Alloy tool (e.g. as in Jackson (2012), a piece of work similar to what is intended in this project). On the other hand, preliminary exercises carried out as lab assignments in the context of model checking (Jackson,2012) have shown that blockchain components such as e.g. blockchain structure can be tackled rather easily and effectively in that way. The main aim of this dissertation is to understand blockchain and other blockchain-based protocols such as e.g. bitcoin and specify its components using the Alloy tool, making it possible to model certain basic rules and concepts about blockchain technology. Thus, through iterative verification, we will face incorrect scenarios and act on them in order to develop models that lead to coherent and error-free blockchains, guaranteeing the reliability and trustworthiness of blockchain technology. This work can be framed in the broad discipline of formal methods applied to software design, stepping up the paradigm of verifying programs and models from logic specifications. 1.3 Dissertation Structure Chapter 2begins by classifying the FMBC workshops by their respective keywords, identifying an opportunity to use model checking in the context of blockchains. Additionally, it introduces the Alloy tool providing a simple example to help the reader to become acquainted with the terminology. Furthermore, it provides a detailed description of the protocol to be modeled, mentioning all the basic concepts behind the blockchain technology. This chapter introduces blockchain and bitcoin, delving into all the topics necessary to understand how modeling is done in later chapters. Thereupon, Chapter 3will introduce an abstract model of a blockchain system expressed in Alloy specification language. Throughout the chapter, instances are highlighted presenting scenarios that are 3 inconsistent with the technology we want to model and so, invariants are iteratively added in order to generate a correct and well formalized final model expressing a complete blockchain structure. Similarly, Chapter 4uses Alloy to guide modeling process of cryptocurrency intuition clarifying how transactions behave in the bitcoin protocol (and other cryptocurrencies). Additionally, Chapter 5specifies how HD Wallets allow a user to have several private keys providing them privacy and security. Finally, Chapter 6examines all the work made throughout this dissertation, evaluates the degree of accomplishment of the initial objectives and proposes the next steps to improve this project. 4 Chapter 2 State of the Art This chapter is devoted to inspecting the state of the art in the research fields addressed in this dissertation. Before approaching a certain topic in some area, it is always advisable to do some research beforehand in order to become familiar with the domain, i.e. its topics, terms and trends. In fact, it is important to conduct a study prior to the development of a research initiative because surveying this literature with no preparation can be a daunting task for novices in the field. 2.1 Preliminary analysis of the bibliography Formal Concept Analysis (FCA) (Ganter et al.,2005) is a mathematical theory that helps to build taxonomical bodies of knowledge. In particular, it can be applied to structure bibliography data (Couto et al., 2011). Following this approach, previous papers published in the FMBC domain have been studied and classified with appropriate keywords, so as to apply FCA in their classification by creating relations among FMBC terms and papers addressing FMBC. To create the concept lattices in this study, we use the “The Concept Explorer” (conexp) tool.1The concept lattice diagram presented in this section organizes the main FMBC terms and relate them. In the lattice, Model Checking (Jackson,2012) refers to a verification technique used to automatically check whether a model satisfies certain properties or specifications. This method is widely applied when a system or protocol correctness and reliability are critical. By analyzing the diagram, we can infer that terms such as blockchain and formal methods are related in the literature, as we expected, but the concepts model checking (and Alloy ) and blockchain are not closely connected. This suggests the use of the Alloy model checker in blockchain technology as an interesting challenge aiming at rigorously guaranteeing its correctness and security. The main aim of this project is to take advantage of the error detection of model checking (Jackson, 1Available in: Conexp tool Site. 5 Figure 1: Lattice diagram structuring the bibliography of FMBC workshops. 2012) — operating with the Alloy tool — and use it in blockchain software development and certification. 2.2 Alloy Overview This section brief overviews Alloy, including its formal verification tool. It is important to note that this summary only covers the fundamental aspects of Alloy and is intended to help readers become acquainted with the terminology. It is not intended to replace the understanding of relational algebra and Alloy, which can be found in Jackson (2012) and Oliveira and Ferreira (2013). Alloy, a formal specification language, was created at the Massachusetts Institute of Technology (MIT). In contrast to traditional programming languages, Alloy is distinctive for its declarative nature, which emphasizes the structural depiction of systems and the formal validation of properties. Using a constraintbased method, it allows users to succinctly articulate the desired properties of a system, as well as the conditions to be avoided. Alloy’s primary benefit lies in its capacity to offer a precise and comprehensible depiction of systems, thereby enabling early-stage analysis and error identification during development. Solvers play a crucial role in Alloy’s effectiveness as a formal modeling tool. In simple terms, a solver 6 is a component responsible for finding solutions to the constraints specified in the Alloy model. Alloy uses a relational logic solver, which is optimized for efficiently solving satisfiability problems. When formulating constraints in Alloy, the solver works to find instances that satisfy these constraints, or, if not possible, to provide information about the inconsistency or unsatisfiability of the model. The solver’s ability to explore solutions efficiently is fundamental to Alloy’s practical usefulness in modeling complex systems. The basic blocks of the Alloy syntax are as follows: Signatures. Signatures define sets of elements in Alloy. For instance, ’sig Car {}’ establishes a set of cars and ’sig Engine {}’ establishes a set of engines. Relations. Relations connect elements defined by signatures. For example, ’sig Car { hasEngine: Engine }’ creates a relationship called hasEngine between cars and engines. Constraints. Constraints, expressed through facts, impose conditions on how elements and relations can interact. For instance, fact EngineMustExist {all c:Car | one c.hasEngine} ensures that every car has exactly one engine. Predicates. Predicates are reusable functions that return a logical value. For example, pred showEngine[c: Car] {some c.hasEngine} can be called to check the existence of an engine in a specific car. Checks and Assertions. Commands like run and check form the linchpin of Alloy’s analysis capabilities. For instance, run showEngine for 3 checks the validity of the showEngine predicate for up to three instances. Let us delve into the capabilities of the Alloy tool by crafting a model that represents a toy banking system with users and cards. This endeavor will provide a briefly exploration of Alloy’s potential in capturing the intricacies of real-world systems. This example serves as a foundational exercise for users to acquaint themselves with the terminology and concepts of Alloy. Its primary purpose is to provide a hands-on familiarity with Alloy’s modeling language and logic, setting the stage for more advanced chapters in the sequel. By navigating through the model of such a banking system, users can gain a practical understanding of how to express and analyze various aspects of a system using Alloy. This preparatory step is instrumental for grasping the intricacies of subsequent chapters in the dissertation, where Alloy will be employed to model and explore more nuanced scenarios. 7 The Alloy Analyser. Let us in the first place introduce the Alloy Analyzer tool, specifically version 6.1.0, which is available here. In Figure 2, we can observe the workspace of the editor, showcasing various features, with a notable emphasis on the ’Execute’ command. This command plays a crucial role, allowing the user to run the introduced Alloy code and analyze the generated instances. Figure 2: Alloy Analyzer workspace After clicking on ’Execute,’ it becomes possible to visualize the instance by selecting the ’Instance’ option — Figure 3illustrates this process. This action provides a detailed view of the generated instance, offering insights into the model’s structure and relationships as Figure 4suggests. Figure 3: ’Execute command’ 8 Figure 4: Alloy instance The ’New’ option of Figure 4provides a new instance of the current model. So, let us proceed with our banking system. In the realm of banking systems, users are pivotal entities that warrant a structured representation. The introduction of the entity Client is the first step in defining the core entity of users within our model. To create the Client entity in Alloy, we can define it as a signature within our model. Figure 5introduces a basic Alloy specification snippet that presents this signature. Figure 5: Signature Client A metamodel in the context of Alloy provides a way to visualize the essential entities of a system and understand how they relate to each other. Think of it as a map that shows the fundamental pieces of the system and the rules governing their interactions. This is helpful because it provides a clear framework for understanding the critical parts of the system and how they fit together. Picture a puzzle: the metamodel defines the available pieces and the rules for connecting them, while the specific model is how you arrange those pieces to create a unique picture of the system. This ensures that the system’s representation is coherent and aligns with design intentions. Figure 6: Initial metamodel To view the metamodel, simply click on ’Execute’ and then select ’Show Metamodel.’ Figure 6shows the metamodel of our current model — signature Client is yet the only entity of our current model. Let us extend it by introducing a ’run’ command to explore instances where there are exactly three clients — Figure 7a shows this constraint. We may ask Alloy Analyzer tool an instance of the model. Result outcome, given in Figure 7b shows a predictable scenario — three clients Client0,Client1and Client2with no relations over them. To provide a more detailed characterization of a banking system, we will introduce the signature Card — representing Card entity — and establish a binary relation cards :Client →set Card to describe the connection between a client and their set of associated cards. This extension provides a more indepth view of the banking system, reflecting the concept that each client may hold a set of cards. When exploring instances of this model, the Alloy Analyzer will consider not only the clients but also the explicit 9 (a) ’Run’ command (b) Banking system - first instance (a) cards specification (b) Extended metamodel relationship between them and their associated cards. In this way, our model now captures in greater detail the dynamics of a banking system, where the Client entity is related to the Card entity through the cards relation, representing the ownership of multiple cards by a client. The Alloy specification for this new relation and its description are presented in Figures 8a and 8b. Figure 9: Banking system - second instance The Alloy instance shown in Figure 9shows three clients and four cards. Relation cards tells us Client0 owns Card3;Client1owns Card1and Card2; and Client2owns Card0. Let us continue showing how to improve an Alloy model by introducing a new feature related to cards. At this stage, each card in the system can have one of two possible states: Unissued or Issued. To capture this information, we will create an abstract entity called Status representing these states and establish a binary relation named status :Card →one Status to associate each card with exactly one state. As signatures Issued 10 (a) status specification (b) New extended metamodel and Unissued are states, we may use the extends keyword to extend these entities along with the abstract keyword to make signature Status abstract — abstract signatures cannot have direct instances; they are designed to be used as superclasses or interfaces for other signatures. Figure 10a presents these concepts specified in the Alloy specification language and Figure 10b shows these new entities and their relations. At this point, we need to validate our current model. Instances in Alloy play a crucial role in preventing undesirable scenarios by serving as concrete representations of a model. Alloy’s instance generation process explores possible combinations of elements within the model to verify the consistency and adherence to specified constraints. This approach helps to identify and mitigate potential issues or undesired situations in the system. Figure 11: Banking system - third instance An instance outcome, seen in Figure 11 shows a client Client1owning a card Card3that is Unissued. This represents an inconsistency since a client should not own unissued cards. Thus, Card2is owned by both Client2and Client0. This is an erratic situation as two different clients must not have the same card — this is known as injectivity in relational algebra and it is central in modeling real-world systems as we will see later in this research. Note that we can compose signatures and relations, e.g. cards :Client →Card can compose with status :Card →Status originating a new binary relation cards.status :Client →Status telling the cards’ status for each client. We can solve the two inconsistencies presented by adding two facts to our model — statements that impose additional constraints or conditions on the instances generated by the model. They are used 11 the input data will change the hash and will get a completely different number unrelated to the previous hash. There is no backward step to use the SHA-256 hash on data input. We can only check by taking the same piece of input data and get the same SHA-256 hash or 256-bit number. If both hash matches, it means the upcoming data is authentic otherwise not. Since the block fields — block number, previous hash, timestamp and data — cannot change, the blockchain protocol introduced the nonce. Nonce is just a random number that miners can continuously change to alter block hashes completely. Therefore, the block hash can vary by varying its nonce. The nonce concept is central for adding a new block to the chain while maintaining the blockchain properties. The Cryptographic Puzzle A node cannot simply encode a block into a hash and then add it to the network. In order to add a new block to the blockchain, the miner needs to find a correct hash by solving a mathematical puzzle to win a competition. There is no way to find any starting and backwards point of the piece of data that gave the hash. Blockchain protocol uses hash cryptography to create a difficult mathematical problem. This problem stipulates that the first miner to produce a hash with a certain amount of leading 0s will be the winner of that block and can add it to the network. Briefly, a miner will keep iterating the nonce value until it produces a valid hash — a hash with certain leading 0s defined by the blockchain protocol. The first miner to submit a golden nonce has the power to add this new block to the chain and collect financial rewards for putting effort into the network. A hash is just a 256-bit sequence of numbers and letters (hexadecimal number), as illustrated in the following equation: 93ef6f358fbb095c608024968630522 (2.1) This number can start with any number 0–9 or letter A–F, so finding a hash that starts with say 17 leading 0s would take a lot of work. It is important to mention that changing a single bit in the nonce value will produce a completely different block hash (the avalanche effect). This prevents miners from cheating — if a single bit change in the nonce value produces a small change in the block’s hash, it would be predictable for miners to produce a golden nonce. Target or difficulty To solve a mathematical puzzle on the network, more and more miners will add their computing power to the network and choose a nonce value that gives them a hash with the correct number of leading 0s. The 18 only way to win a reward over the competition is to use high computing power — high hashrate/hashing power, i.e., tried hashes per second. As more hashing power attempts to solve the puzzle, then this is more likely to be solved faster and faster. The difficulty means how many leading numbers of 0s that miners will need in their hash to claim a valid block. The bitcoin protocol aims to add a block once every 10 min over the long run. In order to maintain this order, the protocol adjusts the difficulty up or down depending on how quickly blocks are added to the network. 2.3.6 Consensus Protocol A consensus in a blockchain is a set of rules to be followed to maintain a blockchain system and reach an agreement on adding new data in distributed nodes. Each node in the network has the same copy of the blockchain and follows the same consensus rules to validate and generate a new block. Without consensus, blockchain is simply a way of storing encrypted/unencrypted data. Consensus allows it to be decentralized because all nodes follow the same rules maintaining uniformity across all copies of a blockchain. Thus, any change in a single blockchain is verified and adopted by another blockchain node in the network. Consensus protocols attempt to answer two main questions: (1) how does the blockchain protect itself from attackers and (2) how does the blockchain address the problem of competing chains. The first one explains how the blockchain reacts when an attacker tries to add a new block with malicious transactions. The second one explains how blockchain leads when there are two or more blockchain versions caused by networks delays (and not by any type of malicious attack). Defense Against Attackers Since miners need to solve a cryptographic puzzle to add a new block to the blockchain, they put a lot of work into the network and this requires time, CPU and energy consumption. A valid hash with a certain number of leading 0s is the proof that miners put effort into the network. Still, miners receive financial rewards for mining a block. The incentive for dedicating computing resources to the network and continually spend energy to verify transactions is the block reward and transaction fees. For each successful block that is added to the blockchain, the miner earns the reward in bitcoin (or other cryptocurrency) as prize for finding the appropriate nonce and its corresponding hash. Therefore, there is a reason for miners to play fair on the network — before each node updates its copy of the blockchain with the new mined block, they perform a series of checks to validate that blocks and their transactions are valid. If a block is not valid, it will be rejected by the network and the miner will not 19 receive the financial reward. It is important to note that mining is resource-intensive, but checking block validity is neither expensive nor computationally heavy. Figure 15 shows part of the list of checks that a network node carries out before updating its blockchain version with a new block. Figure 15: Block validity list Proof-of-Work (PoW) Proof-of-Work (PoW) is a consensus protocol widely employed in many blockchains, notably in Bitcoin and Ethereum, to validate and add new blocks to the blockchain. Its aim is to address the ”resource expenditure” problem by requiring network participants (miners) to demonstrate significant computational work before adding a block to the blockchain. This creates a barrier against arbitrary block creation, preventing malicious attacks. The network sets a target or difficulty criterion that miners must meet when finding a new block. This target is adjusted periodically to maintain a consistent average time between block creations. The more difficult the target, the more computational work is required. Miners compete to solve a complex mathematical problem, often a cryptographic hash function applied to the block header and a value known as a nonce. The goal is to find a nonce that, when added to the block header, produces a hash lower than the target. Once found, the miner propagates the block to the network, and other participants can easily verify if the work was done correctly. If accepted by the network, the miner is rewarded with new units of the native cryptocurrency, in addition to transaction fees. The mining process stimulates participants to invest computational resources in securing the network. There is no formula to calculate a golden hash. It is just a series of hits and trials. This evaluation of nonce to achieve a hash value of the block data is the “work” that miners perform and the right output of the puzzle is the “proof”. Forks After a miner solves the cryptographic puzzle, he can add a block to the chain and broadcast it to the entire blockchain network. Block propagation takes precedence over mining, as an ongoing process of 20 mining a block will be abandoned if the node receives a new block. Suppose a node manages to mine a block Z, and begins distributing it before another recently mined block U, which has been propagated to all the nodes. Then some nodes will append U as the main tip and Z as the side tip while others will do the opposite — a situation known as forking (Mišić et al.,2019). The delay in propagating blocks across the network can lead to a fork, as two or more different miners may find a valid block almost at the same time and try to propagate it. In this situation, there may be several valid version of the chain on the network (competing chains) (Shahsavari et al.,2019). Forks are problematic because the distributed architecture of the blockchain makes it impossible for a node to figure out which of the two otherwise legitimate blocks should be used to extend the chain. Forks lead to a non-consensus situation where participants cannot agree on which chain should be seen as valid (Mišić et al.,2019). According to the so-called Nakamoto consensus , this type of inconsistency is usually solved at the next block as miners select the longest chain. This means nodes continue to mine their main chain (the first chain they receive) and consensus is reached when the next block is mined. The next block is added into one of the possible versions of the chain and the final version of the blockchain is the longest chain, just because it has more accumulated computational power. The branch that has the most valid work dedicated is considered the correct one. Blocks in the rejected branches of the fork are called orphan blocks . Orphan blocks are discarded from the blockchain and are no longer valid blocks. All data included in orphan blocks is invalid as it is not part of the blockchain ledger. Since a fork leads to multiple versions of the chain, the branch most likely to win the competition is the one whose participants’ main chain has the highest hash rate. 2.3.7 Merkle Trees Authenticated Data Structures (ADS) ensure that systems refer to a certain data structure even if only a part of the data structure is known. This brings two benefits: storage and bandwith less consumption by storing only the part of the data structure that identifies it; and part of the structure confidential maintenance (Lochbihler and Marić,2020). Merkle trees are a prime example of an ADS used on blockchain technology. They are binary trees of digests, i.e. cryptographic hashes. Leaves contain data hashes, and inner nodes combine their children’s hashes using a hash function (Lochbihler and Marić,2020). This data structure, put forward by Ralph Merkle in 1979 (Chen et al.,2019), is useful for several application areas such as cryptography and 21 consistency of data content verification. Merkle trees play a fundamental role in blockchain technology by storing a list of transactions identified by the so-called Merkle Root. Figure 16 illustrates the use of Merkle trees in a blockchain. Figure 16: Merkle tree structure Every block on the chain has a Merkle Root that allows every node to verify individual transactions without having to download and validate the entire block. The Merkle Root identifies a list of transations in the network — notably, any alteration in the data of a single transaction induces a change in the Merkle Root, consequently impacting on the hash of the entire block. 2.4 Cryptocurrencies 2.4.1 What is Bitcoin Cryptocurrency in its purest form is a P2P version of electronic cash. It allows online payments to be sent directly from one party to another without going through a financial institution. The network time-stamps transactions using cryptographic proof of work (Nian and Chuen,2015). Bitcoin is a cryptocurrency which, proposed in 2008 by Satoshi Nakamoto, allows users to exchange value without the use of a central authority. Users can participate freely by joining a P2P network with compatible client software (Franzoni and Daza,2022). It is thus a decentralized digital currency that enables instant payments to anyone, anywhere in the world. The primary concern of the bitcoin is that there is no need for a central authority or no government organization to control over it. Using a P2P decentralized technology, it supports different levels of security so that the entire system becomes tamperproof (Aggarwal and Kumar,2021d). Bitcoin can be regarded as a protocol that gives participants a set of rules they can follow to exchange 22 value among them. It was the first cryptocurrency built on top of blockchain to guarantee security and integrity of data. This technology allows users to transact with each other and transactions are stored in blockchain that maintains a all-time record of all transactions. Transfers of value are verified by the network miners and any attempt of malicious transaction will be rejected by the bitcoin blockchain protocol. 2.4.2 Bitcoin’s Monetary Policy The Halving Principle The halving principle dictates that the bitcoin creation is halved every 210.000 blocks. This means that coinbase/block reward given to miners for adding a new block to the chain is halved approximately every 4 years. For example, the number of bitcoins that are rewarded during the mining process gets decreased with a rate of 50% after every 210,000 blocks are created. It approximately takes 4 years to complete this amount of blocks creation. From 2008 to 2012, the block reward fee for one block was 50 bitcoins. Thereafter, from 2012 to 2016 it got reduced to 12.50 bitcoins per block, which was again gradually decreased to 6.25 bitcoins per block for the next 4 years. In this way, the reward for mining a block will get close to 0 by 2140. After some mathematical calculations, it has been found that when the number of bitcoins will reach up to 21 billion in the network, then further no reward will get to the miners from the system. So, by the time passes the number of bitcoins per block will decrease and transaction fees will be increased — just because its estimated network participants will increase and so transaction fees (Aggarwal and Kumar,2021d). And so the financial incentive for mining a block will remain constant over the years. Over the past few years, a per year reduction in number of bitcoins per block and an increase in the cost per bitcoin transaction have been observed as shown in Figure 17. 23 Figure 17: Reduction in number of bitcoins per block Block Frequency A new block is added to the chain every 10 minutes approximately. This is just an average number described in the bitcoin protocol. Bitcoin leads with mining time by adjusting difficulty in cryptographic puzzle solving. If blocks are being mined too fast, the number of leading 0s needed to find a golden hash increases so as to slow time mining down. If blocks are being mined too slow, the number of leading 0s decrease to speed time mining up. This adjustment is made by the bitcoin technology automatically. An average 10 minutes to add a new block is considered a good balance between user experience (participants do not have to wait lots of time) and security. It reduces the probability of competing chains/forks allowing every node to have the most recent version of blockchain. 2.4.3 Understanding Mining Difficulty In the bitcoin standard architecture, the creation of the block rate is adjusted after every 2016 blocks. This block creation takes 2 weeks of the period. The mining difficulty is readjusted every 2016 blocks (Aggarwal and Kumar,2021d). Let us just do some calculations in order to understand how difficult the mining process is. Assume the current bitcoin mining target is 18 leading 0s. Therefore, any nonce that produces a hash with 18 or more leading 0s is a golden nonce. For example, this is a valid hash: 000000000000000000f3a5....94bb 24 Let us calculate the total number of 256-bit hashes, 1664 ≈1.1579 ×1077 ≈1077 and the total valid hashes with 18 leading 0s: 16(64−18) ≈2.4519 ×1055 ≈2×1055 Thus the probability of a valid random picked hash is: 2×1055 1077 ≈2×10−22 ≈0.00000000000000000002% Although the mining process and mathematical puzzle seems to be not that computationally heavy, since miners only need to try different nonces until a valid hash is produced, the probability of a node finding a golden hash is very low. Therefore, miners can form clusters of mining nodes for better computational capacity. By grouping mining nodes into mining pools, miners group their hashing power in order to increase the probability of picking a valid random hash (Raj,2021). 2.4.4 Mining Pools To achieve consensus under the PoW protocol, miners compete against each other to solve a cryptographic puzzle. In theory, the probability of finding a full solution in PoW is proportional to the computational power of the miner. However, the computational power of individual miners is negligible in comparison to that of the network (Can et al.,2022). Therefore, mining alone leads to a highly unstable income and encourages miners to pool their resources and split the resulting rewards. Bitcoin introduces mining pools as groups of miners who combine their hashing power to solve the mathematical puzzle. The mining pool distributes the work among its participants so that no two nodes test the same nonce. Let us try and simplify this concept. For instance, assume a mining pool with 4 participants and 4 billion nonces to try. The mining pool delivers 1 billion nonces to each participant. In this way, there is no repeated work. The rewards — block reward and transaction fees —- are distributed proportionally according to the hashing power of the participants giving to the mining pool. 2.4.5 Nonce Range As unsigned 32-bit numbers, nonce values can vary between 0 and approximately 4 billion. Let us do some estimations. As seen before, with the bitcoin mining target set to 18 leading 0s, the number of 25 invalid hashes is: 1077 −2×1055 The number of possible hashes produced by 32-bit nonce is: 232 ≈4,294,967,296 ≈4×109 Since the number of invalid hashes is much greater than the nonce range, a miner can go through all the nonce spectrum values and still not find a golden nonce. This means that a miner can try all possible nonce values and not solve the cryptographic puzzle. This is a big problem as the mathematical puzzle may be unsolvable and the PoW is impracticable. In fact, blocks in the blockchain have an extra field — the timestamp . The timestamp is the number of seconds that have passed since January 1, 1970 (Unix time). It is updated every second and it is a solution to this problem as it contributes to change a block’s hash. The average modest miner tests 100 million hashes per second. This means that it takes 40 seconds for a single miner to test all 4 billion hashes. Timestamp solves the mining puzzle for individual miners because they do not have enough hashing power to test all nonces in one second. To clarify, let us say a honest miner tries nonce n for timestamp t producing block hash h. In one second, this miner will not try all 4 billion possible hashes and timestamp will update to t+1. Now, nonce n becomes a possible solution for the puzzle, since nonce n and timestamp t+1 will produce a hash other than h. While timestamping constitutes a solution for individual miners, it does not so for mining pools or high hash rate miners. This is because mining pools have so much hashing power that in fractions of a second they can test all 4 billion possible nonces and have to wait for the timestamp to update to retest nonce values again. This way, mining pools waste their hashing power and spend most of their time just waiting for timestamp to update. The solution to this problem will be explained in the next section. 2.4.6 How Miners Pick Transactions Each node in the blockchain network has a memory pool called mempool . A mempool is a list of unconfirmed transactions that can be chosen by miners. As soon as a user wants to make a bitcoin transaction, the transaction will be inserted into each participant’s mempools. Apart from other information (detailed in the sequel), each transaction has an associated fee that is rewarded to the block miner for putting effort into the network. When a miner wants to add a new block to the chain, he chooses a certain number of transactions based on higher fees as this will contribute to his reward. The problem of high hash rate miners described above now has a solution. As transactions become 26 part of the SHA-256 input, this contributes to changing the block’s hash. Mining pools select transactions based on higher fees and begin to solve the cryptographic puzzle. In less than a second, all 4 billion possible nonce values will be tested and all hashes produced are very likely to be invalid. In order to mining pools not have to wait for timestamp update to test all nonces again wasting most of their time, they just change the block configuration — the lowest fee transaction included in the block is swapped by the highest fee transaction in the mempool not included in block. The puzzle solving procedure retakes for all nonces before timestamp increments. Mining pools change block configurations repeatedly until hashes are valid or the timestamp gets updated. 2.4.7 How Do Mempools work In the Bitcoin protocol, the memory pool (mempool) acts as a repository of all unconfirmed transactions waiting to be added to a block. Once a user generates a transaction, it is broadcast to the entire network and stored into the mempool where it awaits confirmation (Saad et al.,2018). Each network participant has a mempool where transactions made by users are stored. Before any transaction is added to a user’s mempool, several checks are performed in order to ensure its validity. A bitcoin node validates each transaction it receives before relaying it to its peers. A valid transaction must have correct signatures, and must only spend existing and currently-unspent coins. Otherwise the transaction will be discarded and will not be propagated further (Delgado-Segura et al.,2018). Some checks that are made are described below: •Syntax and Structure: The transaction must have a valid syntax and structure, following the format defined by the blockchain protocol. •Digital Signatures: The signatures associated with transaction entries must be valid. •Input/Ouput Values: All values transacted must be positive. Mempool transactions are selected by miners to be included in a block. Once a new block is joined to the chain, it is propagated to the blockchain network via flooding. When a node gets a new block mined, all transactions in the block are deleted from its mempool. This process helps clear users’ mempools of already confirmed transactions. 2.4.8 Orphaned Blocks As mentioned previously, orphan blocks are originated by competing chains. Rejected fork branches produce blocks that are considered invalid as they are no longer part of the blockchain. 27 2.5.5 Public Key v Bitcoin Address Nagata et al. (2018) tells a bitcoin address is a hash value specified by applying the SHA256 secure hash function to a target public key. It is known that it is impossible to invert the address generation process to obtain the public key from the address. Despite this, it should be noted that the process is deterministic. Therefore, the owner can be easily identified even if the corresponding public key is unknown. Since the Elliptical Curve Digital Signature Algorithm (ECDSA) (Aggarwal and Kumar,2021b) generates public keys from private keys and in order to additionally provide another layer of security, bitcoin addresses are used to transact value. Although it is possible to send money directly to a public key, this process is unusual and participants prefer to transact via addresses. A private key must be secret and known only by the person who owns it, but public keys and bitcoin addresses are not. In fact, participants can share their public key and bitcoin address either to receive or send money. Bitcoin addresses were introduced to add some additional security and privacy to the network. Therefore, users generally do not expose their public keys in order to protect the link between public and private keys. Since a transaction needs to include the sender’s public key to verify its digital signature, a public key is only exposed when an user wants to send money. To receive bitcoin value, a participant does not need to share his public key and instead communicates his bitcoin address. A private key unlocks all funds from the bitcoin address it generates and so SHA-256 applied to a public key to produce an address constitutes an extra security feature provided by the bitcoin protocol. 2.5.6 Hierarchically Deterministic (HD) Wallets According to Das et al. (2023), a hierarchical deterministic wallet scheme is organized in a treelike structure, where one root wallet deterministically derives child wallets which in turn deterministically derive further child wallets. Futhermore, a Bitcoin wallet is a set of private keys known to a user and which allow that user to spend any Bitcoin associated with those keys. In a hierarchical deterministic (HD) wallet, child private keys are generated pseudorandomly from a master private key, and the corresponding child public keys can be generated by anyone with knowledge of the master public key. These wallets have several interesting applications including Internet retail, trustless audit, and a treasurer allocating funds among departments (Gutoski and Stebila,2015). This design offers considerable advantages in terms of security, since the exposure of one derived key does not compromise the others. The ability to create an unlimited number of addresses from a single seed gives HD Wallets unique scalability. This not only simplifies the user experience, but also improves his privacy, as addresses can 34 be used in isolation for specific transactions. Thus, the creation of new addresses for both sending and receiving funds makes it difficult to monitor transactions by address. It becomes unpredictable for a malicious user to inspect transactions for a given address, contributing to the security and privacy of the network. Figure 21 represents HD Wallets scheme describing how a master private key can derive multiples private keys. The links between the master public keys and their respective public keys are hidden for visual simplicity. Figure 21: HD wallets scheme 2.6 Summary This chapter presented a comprehensive account of the foundational concepts underpinning blockchain and bitcoin. The literature review delves into the core principles that define these revolutionary technologies. Concepts such as decentralized consensus, cryptographic hashing, and the structure of blocks and transactions are elucidated. The historical context of blockchain’s emergence and the transformative impact of bitcoin on the financial landscape are also discussed. This was preceded by a brief introduction to Alloy based on a simple example modeling a basic banking system. This introductory example aims to familiarize readers with Alloy, setting the stage for its use in modeling blockchain and bitcoin protocols in the following chapters of the dissertation. 35 Chapter 3 Modeling Blockchain Basics This chapter will introduce our abstract model of a blockchain system expressed in the Alloy specification language. The Alloy model checker will be used to guide the modelling process in order to timely discard undesirable or inconsistent scenarios about the blockchain structure. This will be achieved by piecewise addition of invariants i.e. desirable formal properties about the model. The final result is a well-formed blockchain model which features all the basic rules of the technology thus formalized. Note that throughout chapters 3,4, and 5of this dissertation, multiple Alloy instances are generated to illustrate different scenarios. To enhance visual clarity for readers, certain relations are selectively omitted in each instance. The focus is on presenting only the essential relations relevant to the specific context, simplifying the visual representation and aiding in a clearer understanding of key aspects in each scenario. This tailored approach aims to balance the conveyance of crucial information while ensuring that the visual presentation remains accessible to the audience. 3.1 Towards a Basic Blockchain Model Figure 22: The Block signature and its Next relation Recall that a blockchain system is simply a chain of blocks. Thus our first entity is the Alloy signature Block of figure 22, which is equipped with the binary relation Next :Block→Block telling which block is next in the chain. The first block of the chain is called the Genesis Block and has no previous block. In our Alloy model (22), BlockI stands for Genesis Block and extends any normal block since it is a block, too. What does the Alloy model checker ”thinks” of this 36 initial design? By asking the tool for an instance of the metamodel, the outcome given in figure 23 is clearly unfit for our purposes, because a block can have at most one next block. This can be specified easily by adding a lone cardinality constraint to the Next relation: sig Block{ Next :lone Block } one sig BlockI extends Block{} Figure 23: Blockchain model - first instance In all instances presented by the Alloy tool, we need to classify blocks into two groups: effective blocks and non effective blocks. A block is an effective block if it is consummated in the chain — it has a previous or a next block. Otherwise it is regarded as a non effective block. Both sets of blocks are specified in Alloy as follows: fun effectiveBlocks :set Block {Next Block +Block Next } fun nonEffectiveBlocks :set Block {Block −effectiveBlocks } As is to be expected, running the model with no more restrictions leads to further inconsistencies. The following paragraphs will unveil the inconsistencies found by Alloy and how adding suitable invariants counter such undesirable scenarios. Figure 24: Blockchain model - second instance Irreflexivity of Next.Now that for each block, there is at most one block in the Next relation, let us run the model to check if there is any inconsistency. The next outcome given by Alloy tool, seen in figure 24, shows some of them. Let us deal with each inconsistency one at a time. 37 This instance shows that Next includes the Block2→Block2relationship. This means that Block2 has Block2itself as the next block, which would lead to an infinite chain. To avoid this, we need to add another property to the model: pred propNoConfusionNext {no Next &iden } In relation algebra, this property is known as irreflexivity (Oliveira,2019). Injectivity of Next.The instance of figure 24 also shows the Block0→Block2and BlockI→Block2 relationships meaning Block0and BlockI both have Block2as next block. As the Next relation must be injective (Oliveira,2019) — two different blocks cannot have the same block as next block — the corresponding property is added to the model: pred propInjectiveNext {Next ~Next in iden } Figure 25: Blockchain model - third instance BlockI as first block. Figure 24 displays another possible inconsistency: BlockI must be the first block on the chain. We need to guarantee that the Next relation does not have the AnyBlock→BlockI relationship. Let us force this scenario by pushing a property to the model: pred propInitialBlockI {no Next BlockI } Now that these basic fixes are done, let us ask for other instances of the model to check if any other inconsistencies about the blockchain structure are found. Figure 26: Blockchain model - fourth instance Next should be acyclic. As we can see in the instance prompted by Alloy given in figure 25, the model is still inadequate. First of all, a blockchain should not have 38 cycles in it — the chain should have a beginning block BlockI and a last block mined. Let us enforce this property into the model: pred propNoCycleChain {no ^Next &iden } Reachability from BlockI. Figure 26 displays another instance given by the Alloy model checker after adding the previous property. The inconsistency shown this time is that every block should be reachable from BlockI, and the opposite is shown in the instance: BlockI is actually separated from the chain of the other blocks. Let us modify the model by adding a property to get rid of this undesirable scenario: pred propReachableFromBlockI {all b:effectiveBlocks−BlockI |bin BlockI ^Next } Figure 27: Blockchain model - fifth instance After enforcing all properties described above, the model begins to obey the basic rules described in blockchain protocol, as shown in the instance given in Figure 27. Now the chain of blocks is meaningful, linked and reachable from its Genesis Block. Further instances provided by Alloy seem to model the blockchain protocol adequately. Recall that model checking never shows the absence of inconsistencies, only their presence , as illustrated above. Nevertheless, adequate instances give confidence that the formal design is on the right track. 3.2 Criptographic Hashing Figure 28: Metamodel extension with the hash and previous relations Recall from section 2.3.3 that each block in the chain should point to its previous block through some hashing process . Bearing this in mind, two new binary relations are added to the previous block model that require the declaration of a new signature, Word, representing 32-byte hash values. Figure 28 describes the new binary relations 39 in the Block signature: (a) the relation hash :Block →Word compresses a block in a hash; and (b) the relation previous :Block →Word gives the hash of the previous block. Once again, let us see what the Alloy model checker ”thinks” of these new relations by asking the tool for an instance of our extended metamodel. The instance given in Figure 29 is clearly wrong because there are blocks with more than one hash and more than one previous hash. This is an inconsistency, as each block must have at most one hash and at most one previous hash. We need to specify this constraint in the model and this can be done easily by adding lone cardinality constraints to the Block signature: sig Block{ Next :lone Block , previous :lone Word , hash :lone Word } Figure 29: Blockchain model - sixth instance No previous hash in BlockI. The instance of Figure 29 unveils other inconsistencies: previous holds the BlockI → Word0relationship meaning BlockI has Word0as previous block hash. BlockI is the first block on the chain and so it has no previous block. Therefore, BlockI should have no previous block hash, a property enforced in as follows: pred propNoPrevBlockI {no BlockI previous } Injectivity of hash.Moreover, Figure 29 shows that hash includes the BlockI→Word1and Block→Word1relation- ships, meaning both BlockI and Block have Word1as block hash. That is called a collision and should not be present in blockchain protocol. What is required is that the hash relation be injective – two different blocks should not have the same block hash. The most direct way to specify relation injectivity is to ensure that relation kernels are at most the identity (Oliveira,2019), as shown in the following invariant added to the model: pred propInjectiveHash {hash ~hash in iden } 40 Figure 30: Blockchain model - seventh instance Disjointness of hash and previous.Proceeding the detection of possible, further inconsistencies in the updated model by inspection of the instances prompted by Alloy, Figure 30 shows yet another one: since the previous relation gives the previous block hash and the hash relation gives the current block hash, these hashes can never be the same. In the instance shown, both relations have Block →Word0 relationship meaning Block has hash Word0and previous hash Word0. We need to ensure this does not happen, as specified in yet another property added to our model: pred propNotSameHashPrev {all b:effectiveBlocks−BlockI |bhash != bprevious } Figure 31: Blockchain model - eighth instance Cryptographic chaining. All we have been doing throughout this section is to improve an Alloy model by inspecting the instances given by the Alloy analyser after each desirable property is added to the model. Given at the current stage in this process, the instance of figure 31 shows the model is still unfit for our purposes. The Block0→Block1relationship holds in the Next relation and yet the previous hash of Block1 does not match the hash of Block0. Fortunately, this inconsistency between the actual chain (cf. Next) and its cryptographic chaining (cf. hash and previous) is easy to enforce: pred propLinkedChain {Next in hash ~previous } Eventually, the piecewise improvement of our starting model shows a fruitful outcome in the instance given in Figure 32. This shows a chain of blocks that is cryptographically linked as the blockchain technology requires: the hash and previous relations show how the three blocks are linked to each other through the correct encryption. 41 3.3 Nonces Figure 32: Blockchain model - ninth instance As part of the PoW mathematical problem, recall that miners need to keep iterating a value called nonce to solve a cryptographic puzzle — see section 2.3.5. Thus we need to add noncing to our model. Before extending the block concept, let us just add a new signature Nonce shown in Figure 33. To verify whether a nonce is valid, we need to create a new binary relation validHash : Nonce→Bool that determines whether the nonce produces a valid hash. The signature Bool represents a Boolean and can have two different values —True or False. Next, let us add two new binary relations to our signature Block: (a) nonce :Block →Nonce representing the block’s current nonce; and (b) triedNonce :Block →Nonce recording every nonce attempted by a miner for a block. Figure 33: Metamodel extension with validHash,triedNonce and nonce relations Let us see how the Alloy model checker handles these relations by asking the tool for an instance of the extended metamodel. The result, given in Figure 34, is not suitable for our purposes, since the nonce 42 relation has the Block →Nonce0and Block →Nonce1relationships meaning Nonce0and Nonce1 are Block current nonces. This is an inconsistency, as each block has exactly one nonce. Therefore, we have to add one cardinality constraint to the nonce relation: sig Block{ Next :lone Block , previous :lone Word, hash :lone Word, triedNonce :set Nonce , nonce :one Nonce , } Figure 34: Blockchain model - tenth instance Visual simplification. Figure 34 illustrates an effective block Block that attempted some nonce Nonce0. To enhance visual simplicity in the model, let’s assume that effective blocks do not display tested nonces but only present the valid nonce. Moreover, we will enforce that effective blocks must have both a hash and a previous hash. Consequently, noneffective blocks do not possess previous and current block hashes: pred propEffectiveBlocks{ all b:effectiveBlocks−BlockI |one bprevious all b:effectiveBlocks |one bhash all b:effectiveBlocks |no btriedNonce } propNonEffectiveBlocks{ no nonEffectiveBlocks previous no nonEffectiveBlocks hash } 43 tnot in Block tx bnonce validHash =True wnot in (Tx merkleRoot +Block hash) //effects previous' = previous +b→lastBlock hash hash' = hash +b→w tx' = tx +b→t Next' = Next +lastBlock →b triedNonce ' = triedNonce −b→btriedNonce //frame conditions nonce ' = nonce } 3.5.3 Visualization of Mining Process using Alloy Instance This section embarks on a journey to depict the mining process as a sequence of states, dynamically transitioning from one to another. Leveraging the expressive capabilities of Alloy’s formalism, we utilize instances to vividly showcase the temporal dynamics inherent in mining, including the selection of transactions, the search for a valid nonce and the verification and addition of blocks to the blockchain. As we navigate through this Alloy instance, each snapshot captures a distinct moment in the mining journey, providing a visual narrative of how the system unfolds over time. The visualization not only facilitates a deeper understanding of the intricate details of the mining process but also delves into the behavioral aspects inherent in the mining process. In the presented Alloy instance, our exploration centers around the nuanced landscape of the blockchain mining process, with a particular emphasis on the genesis of a new block. To capture the dynamic nature of this process, let us add the var keyword to the Next,hash,previous,tx,nonce and triedNonce relations indicating the variability of these relations over time. Additionally, let us apply the always keyword to all properties of the system in order to make them verifiable across all states of the instance — we establish a persistent commitment to certain properties throughout the entire evolution of the system. Next, we compel the model to iteratively perform one of three possible actions in each state: either do nothing (given by the nop predicate); or a block attempts a nonce (given by the findGoldNonce predicate); or a block is added to the chain (given by the addBlock predicate). The nop predicate represents the scenario in which nothing occurs, and the system’s relations remain unchanged: 50 pred nop { nonce ' = nonce tx' = tx previous' = previous hash ' = hash Next ' = Next triedNonce ' = triedNonce } fact Traces { always (nop or some b:Block ,t:Tx,w:Word |addBlock[b,t,w]or some b:Block ,n:Nonce |findGoldNonce[b,n]) } Initial state definition. Let us define an initial state, encapsulating crucial parameters that govern the early dynamics of the system. In this initial state, we commence with a blockchain ecosystem featuring two non-consolidated blocks. These blocks represent a nascent stage where certain blocks are yet to be fully integrated into the blockchain structure. To further characterize this state, we instantiate the relationship between attempted nonces and blocks, expressed by the triedNonce relation: fact Init { #nonEffectiveBlocks = 2 triedNonce = {b:Block ,n:Nonce | bin nonEffectiveBlocks and nin bnonce} nonEffectiveBlocks nonce validHash in False #invalidNonces = 4 #validNonces = 2 } Specifically, for each non-consolidated block, the attempted nonce set only includes its current nonce. In shaping the cryptographic landscape, we declare that all nonces from non-consolidated blocks generate invalid hashes, setting the stage for the exploration of nonce validation within the mining process. Additionally, we introduce the concept of nonces producing either valid or invalid hashes. Four nonces are designated for generating invalid hashes, while two nonces contribute to the creation of valid hashes. This distribution establishes an initial balance in the cryptographic attempts within the system. This meticulously defined initial state serves as the bedrock for our subsequent analyses and simulations, laying the groundwork for unraveling the evolving dynamics of the blockchain system. 51 Figure 40: Instance analysis - first iteration Run command. The primary objective of this Alloy run is to ensure the seamless integration of every block within the blockchain mandating that every block must, at some point in its evolution, transition from a non-consolidated state to being an effective block within the blockchain contributing to the continuous formation of the blockchain structure. Additionally, we push a constraint explicitly mandating that all invalid nonces undergo exhaustive testing until they are eventually associated with the set of attempted nonces within a block. This is introduced to enhance the reader’s comprehension, providing a nuanced perspective on the intricate process of nonce testing within the mining procedure: run{ all b:Block | eventually bin effectiveBlocks all n:invalidNonces | eventually nin Block triedNonce }for 5but exactly 5Block , exactly 12 Word , exactly 6Nonce , exactly 5Tx Instance analysis. Figures 40 to 46 show the evolution of the current instance under examination. One can see the model unfolding itself to reveal a blockchain configuration characterized by a total of three consolidated blocks BlockI,Block3and Block2, further to the two blocks Block0and Block1engaged in the cryptographic challenge of discovering a hash below the specified target. Figure 40 shows Block0 52 Figure 41: Instance analysis - second iteration and Block1are trying nonces Nonce2and Nonce3that produce invalid block hashes. Therefore, they need to keep iterating nonce value to find a golden nonce. Figures 40 to 44 depict the iterative nature of the mining process for Block0and Block1. Initially, Block0and Block1attempt nonces Nonce2and Nonce3, respectively, leading to invalid block hashes. Subsequently (Figure 41)Block1successfully discovers a golden nonce, Nonce4, resulting in a hash below the target. As a result, Block1can be added to the blockchain. On the other hand, in Figure 42 Block0experiences an unsuccessful attempt with Nonce1, needing further iterations to find a suitable nonce. Figures 43 and 44 document additional nonce attempts for Block0, with Nonce0yielding an invalid hash, and finally, Nonce4leading to a successful golden hash. Figures 45 and 46 capture the integration of Block0and Block1into the blockchain, respectively. Each block establishes a hashing linkage with its previous block, creating a well-formed and interconnected blockchain structure. The final state, given in Figure 46, showcases a blockchain composed of five blocks. This final configuration adheres to the inherent principles of blockchain architecture, where each block is linked to its predecessor through cryptographic hashes, providing a secure and immutable ledger. 3.6 Summary In this chapter, the dissertation takes a computational dive into the intricacies of blockchain, employing the Alloy modeling language to spotlight the crucial cryptographic connections that define its structure. 53 Figure 42: Instance analysis - third iteration Figure 43: Instance analysis - forth iteration 54 Figure 44: Instance analysis - fifth iteration Figure 45: Instance analysis - sixth iteration 55 Figure 46: Instance analysis - seventh iteration The modeling process meticulously unveils the cryptographic linkages within the blockchain. The chapter unfolds with a detailed exploration of how each block forms an unbreakable bond with its antecedent, securing the integrity and immutability of the entire chain. The resulting Alloy model encapsulates the essence of cryptographic linkage, laying the groundwork for subsequent analyses and validations and making a contribution towards a robust and secure representation of blockchain dynamics. 56 Chapter 4 Modeling Basic Cryptocurrency Transactions This chapter builds upon the model developed in chapter 3and approaches a specific branch of the blockchain protocol —- cryptocurrencies. Cryptocurrencies extend blockchain technology by storing transactions in the body of blocks. As in the previous chapter, the Alloy model checker will be instrumental in driving the overall modelling process towards an adequate, type-safe, and flawless model as much as the inspection of model instances permits. 4.1 Data Storage - Transactions Figure 47: Initial metamodel This chapter will fully detail the transactions intuition by extending the Tx signature seen in chapter 3. To enhance the visualization of the model and its instances, we will omit some Block relations that are not important for modeling the transaction intuition. Therefore, the triedNonce,nonce,previous and hash relations are not shown at this stage, keeping only how blocks are linked through the Next relation and the tx and merkleRoot relations. At this point, figure 47 shows our starting metamodel with Block,BlockI,Tx and Word entities and their relations. Obviously, we need to keep Next,tx and merkleRoot invariants (detailed in chapter 3) to avoid inconsistent scenarios. Remember that each Bitcoin block stores a list of transactions. So, let us extend the Tx signature by equipping it with a new binary relation, transaction :Tx→Transaction, recording the set of transactions it stores. The signature Transaction implicitly created models a single transaction and is equipped with 57 a new binary relation txid :Transaction →Word declaring the transaction hash. Figure 48: transaction and txid relations Figure 48 shows the model enriched with new signature Transaction and the txid and transaction relations. The instance immediately prompted by the Alloy analyser, seen in figure 49, unveils an inconsistency that was to be expected recalling the experience of the previous chapter: a transaction must have exactly one hash. Thus, the txid relation should be a function which, using Alloy cardinality keywords, is specified by txid :Transaction →one Word. So our starting model is subject to its first improvement: sig Tx{ merkleRoot : one Word, transaction : set Transaction } sig Transaction{ txid : one Word } Figure 49: Transactions model - first instance Non-empty transaction list & disjointness of merkleRoot and txid. The inspection of figure 49 also shows that Tx0stores no transactions. This is an inconsistency as a block needs to store a non-empty transaction list. Also, txid holds the Transaction →Word2 relationship meaning that Word2is aTransaction hash and merkleRoot has Tx0→Word2relationship meaning Word2is Block Merkle root hash. This is incoherent because SHA-256 produces different hashes for different inputs. This Alloy instance 58 does not describe the Bitcoin (and other cryptocurrencies) behaviour and so let us add some properties leading to this scenario: pred propAtLeastOneTransaction { all t:Tx | some t.transaction } pred propDisjMerklerootTxid { no Tx.merkleRoot & Transaction.txid } Figure 50: Transactions model - second instance More injectivity constraints. Figure 50 shows an instance of the model issued after adding the properties above. The problem now is that different transactions should have different hashes — Transaction1and Transaction0have the same hash Word3. Furthermore, two different blocks (BlockI and Block0) store the same transaction Transaction1, which is another incoherence. As before, we fix this by ensuring that the txid and transaction relations are injective: pred propInjectiveTxid { (Transaction<:txid).~(Transaction<:txid) in iden } pred propInjectiveTransaction { transaction.~transaction in iden } 4.2 Inputs and Outputs At this point, let us remember the transaction constitution. Recall from sections 2.5.1 and 2.5.2 that a transaction consumes a set of inputs that refer to the outputs of other transactions and produces a set of outputs that can feed another ones. Additionally, a user assigns a fee to the transaction to reward miners for putting effort into the network. 59 Figure 60: Transactions model - eighth instance and the auxiliary predicates nonUsedHashesMrTxid and afterSndBlock can be found in section A.2 of the appendix: pred propInputsFirst2Blocks { inputsFromBlocks[Block-afterSndBlock].txid in nonUsedHashesMrTxid } Let us analyse a concrete Alloy instance to understand and clarify the introduction of the property above. The result outcome, given in figure 60, reveals that txid :Input →Word relation holds both Input1→Word7and Input0→Word7relationships. Word7lacks of apparent significance. These hashes are intentionally introduced to reserve a distinct set for the initial inputs, ensuring they do not conflict with other meaningful hashes within the model. This strategic allocation serves the purpose of preventing inadvertent clashes with relevant hashes in the model, maintaining the integrity of the representation and avoiding any unintended interference with the model’s structure and semantics. Input/Transaction referencing. As Figure 60 shows, the txid :Input →Word relation has the Input2→Word6relationship, meaning that Input2refers to an output created in a transaction whose hash is Word6. That is illegal in the bitcoin security system, since no previous transaction has the Word6 66 hash and so no output fed Input2. Forcing an input to always refer to exactly one past transaction is the aim of yet another model invariant. The definition of the auxiliary function precTxFromInput and the auxiliary predicate inputAfterSndBlock can be found in section A.2 of the appendix: pred propSequenceInput { all i:inputAfterSndBlock | one t: precTxFromInput[i] | i.txid = t.txid } After adding this property, let us once again check if the model is well-formed by asking the Alloy tool for new instances of the current model. In the instance shown in Figure 61, inputs of the two beginning blocks BlockI and Block0do not refer to any previous transactions and the only non-beginning block Block1 has a single transaction Transaction0that includes Input2fed by an output created in Transaction2 of BlockI. Let us detail this using the relational approach: txid :Input →Word has the Input2→Word6 relationship, meaning that Input2was fed by an output created in the transaction whose hash is Word6; and txid :Transaction →Word has the Transaction2→Word6relationship meaning that Word6 is Transaction2hash and so Input2refers an output created in Transaction2. Figure 61: Transactions model - ninth instance 67 4.2.2 Output Details As Figure 56 suggests we need to detail the Output signature by equipping it with two new binary relations: (a) value :Output →Int recording the number of satoshis being transferred; and (b) to :Output → BAddr indicating the receiver’s bitcoin address. Figure 62 represents the final (meta)model in which the Output signature has theses new relations. Figure 62: Final metamodel Still, the current model is not consistent, as shown in the instance of figure 63, and the problem is again a cardinality one: the to relation holds the Output →BAddr0and Output →BAddr1relationships, meaning both BAddr0and BAddr1receive the funds present in Output – that is an inconsistency since an output must have exactly one receiver. Moreover, an output must transfer exactly one value, and in the value relation we see Output → −3and Output → −4. Thus the following change in the Output signature: sig Output{ value : one Int, to : one BAddr } 68 Figure 63: Transactions model - tenth instance Transact positive values. Throughout this section, we have ignored an inconsistency shown in several Alloy instances. Figures 58 and 63 show some transacted values are negative. Clearly, these scenarios are inappropriate since all input, output or fee components must transact positive values. Thus we have to restrict the previous model by specifying a new invariant in order to rule out such undesirable scenarios: pred propPositiveValues { all iv : Input.value, ov : Output.value, f : Transaction.fee | iv>0 and ov>0 and f>0 } Let us ask Alloy tool for an instance to check if our current model is coherent. Figure 64 shows a consistent scenario by only providing positive values in input,output and fee relations. Input, output and fee balance. As mentioned in section 2.5.2, a transaction consumes value from its inputs providing value to its outputs. A transaction fee corresponds to the difference between its input value and its output value and it is rewarded to miners for putting effort into the network. 69 Figure 64: Transactions model - eleventh instance The instance outcome given in Figure 64 shows a situation that is undesirable in the bitcoin protocol. One can see that Transaction0 is composed by one input Input1consuming 7 satoshis and one output Output transacting 5 satoshis to a bitcoin address. Thus, Transaction0 fee is incorrect: instead of 4 satoshis it should be 2 satoshis in order to obey the fee principle. Thus, we need to enforce this rule for each transaction on the system. The definition of auxiliary functions sumInputValues and sumOutputsValuesFee can be found in section A.2 of the appendix: pred propBalanceValues { all t:Transaction | sumInputValues[t] = sumOutputsValuesFee[t] } Figure 65 shows this fee principle being checked. The non-beginning block Block1includes Transaction0 with one input Input2and one output Output0. Thus, Transaction0has 4 satoshis fee, Input2is consuming 5 satoshis and Output0is transacting 1 satoshis. Input/Output referencing. As mentioned in section in Input/Transaction referencing, an input refers to a previous transaction through the txid :Input→Word relation. Suppose txid has a Input1→Word1 relationship, meaning that a transaction with hash Word1created an output Output1that is feeding Input1of another transaction, and then Output1references Input1. Therefore, Input1sender should match Output1receiver and Input1consuming value should match Output1transfer value. The scenario of Figure 65 is inconsistent in this respect, since Input2was created in Transaction1 and has Output1as his referenced output since it is the only output of Transaction1. Although Input2 consumed 5 satoshis from BAddr0, its referenced output Output1sent 4 satoshis to BAddr1. Therefore, we need to force that if Input1and Output1are a referenced Input/Output then the Input1and Output1parameters must match. Let us push an invariant into the model that ensures this. 70 Figure 65: Transactions model - twelfth instance The definition of the auxiliary function originTx and the auxiliary predicate inputAfterSndBlock can be found in section A.2 of the appendix: pred propReferenceInputOutput { all i:inputAfterSndBlock | one o: originTx[i].output | i.value = o.value and i.sender = o.to } The instances produced by the Alloy model checker hereafter suggest that one may have reached an adequate model for the bitcoin protocol. Such is the case of figure 66. The first two blocks have special transactions and the following ones store transactions that refer to previous ones through inputs and outputs. The specification process has lead to a type-safe model covering some basic concepts of cryptocurrency transaction intuition. 71 Figure 66: Transactions model - thirteenth instance 4.3 Summary In this chapter, an exhaustive exploration unfolds as Alloy modeling takes center stage to intricately depict the nuanced world of cryptocurrency transactions, with a particular emphasis on the renowned Bitcoin system. The detailed Alloy model meticulously captures the essence of these transactions, focusing on the interplay between inputs and outputs, fundamental components that define the cryptoeconomic landscape. The chapter unravels the intricate dance between these transactional elements, showcasing how inputs are linked to outputs, illustrating the transfer of cryptocurrency values within the blockchain. The model places a spotlight on the transparency, security, and decentralized nature inherent in cryptocurrency transactions, unraveling the layers that contribute to the robustness of blockchain networks. Through the lens of Alloy, the chapter not only provides a comprehensive understanding of the transactional dynamics but also lays the groundwork for subsequent analyses and validations. This meticulous Alloy model becomes a valuable tool in unraveling the complexities of cryptocurrency transactions, offering insights that extend beyond theoretical frameworks into practical applications within blockchain systems. 72 Chapter 5 Modeling HD Wallets The primary objective of this chapter is to delve into the intricacies of Hierarchical Deterministic (HD) wallets, elucidating their structural composition through a meticulous modeling process. In alignment with our established methodology in preceding chapters, we will employ the Alloy tool to conduct this modeling endeavor. The ultimate goal is to craft a precisely defined model that not only captures the essence of HD wallets but also encapsulates their inherent behavior. As before, the modeling journey will unfold iteratively, starting with the definition of signatures to represent the constituent elements of HD wallets, including key components such as hierarchical levels, keys, and deterministic relationships. We will subsequently introduce relations to establish the intricate connections between these elements, and employ constraints to encapsulate the specific rules governing HD wallet behavior. 5.1 Private and Public Keys Figure 67: The generates relation and its signatures Recall from section 2.5.4 that every user entering the bitcoin network is assigned a private key that generates a public key. Thus, our first entity is the Alloy signature PrivateKey present in figure 67, which is equipped with the binary relation generates :PrivateKey → PublicKey telling the public key generated by a private key. Therefore, we need to create a signature PublicKey which represents a public key. To gain insights into Alloy’s interpretation of the introduced relation, we seek to scrutinize the model by requesting an instance using the Alloy tool. The result, presented in Figure 68, reveals an undesirable scenario where a private key seemingly generates 73 more than one public key. To rectify this discrepancy, we propose a specific constraint in the form of a model invariant by adding the one cardinality to the PrivateKey signature: sig PrivateKey{ generates : one PublicKey } sig PublicKey{} Figure 68: HD wallets model - first instance Injectivity of generates.Given that the algorithm for generating a public key from a private key is deterministic in nature meaning it consistently produces a unique public key for a given private key, the model should grant the injectivity of the generates relation. This ensures that two different private keys never yield the same public key. The Alloy instance outcome, as depicted in Figure 68, highlights this inconsistency: PublicKey1 is purportedly determined by two distinct private keys, namely PrivateKey0and PrivateKey1. This deviation from the expected behavior necessitates the imposition of an additional invariant to rectify the situation: pred propInjectiveGenerates { generates.~generates in iden } By enforcing the properties detailed above, the model now adheres to the very basic rules of the private and public keys protocol, as illustrated in the instance of Figure 69. Thus the generates relation adequately encapsulates the fundamental cryptographic operation where a private key acts as the generator for its associated public key. Figure 69: HD wallets model - second instance 74 5.2 Addresses In the Bitcoin network, when a transaction occurs, it is intended for a specific address. This address is determined by the user’s public key, as outlined in Section 2.5.5. In essence, each user’s public key serves as the determining factor for the address to which they will receive funds in the network. Figure 70: The addresses relation and its signatures To enhance our model, we extend the PublicKey signature by introducing a new binary relation, denoted as addresses :PublicKey →BAddr, indicating the bitcoin address determined by a public key. Figure 70 illustrates our augmented metamodel with this new relation. Upon seeking insights from the Alloy model checker through an instance request, as depicted in Figure 71, two inconsistencies surface. Specifically, the instance reveals a situation where a public key appears to address more than one bitcoin address. As before, the solution is straightforward: just restrict the PublicKey signature with a one -cardinality constraint. sig PublicKey{ addresses : one BAddr } Figure 71: HD wallets model - third instance Injectivity of addresses.The other inconsistency arises from the fact that, due to the SHA-256 algorithm, a bitcoin address should uniquely correspond to a single public key. To rectify this, we must ensure that the relation addresses is injective, signifying that each bitcoin address is determined by only one public key. By enforcing injectivity again, we address the inconsistency and align the model with the deterministic nature of the SHA-256 algorithm in Bitcoin address conversion. pred propInjectiveAddresses 75 Chapter 6 Conclusions and future work This final chapter looks back and evaluates the progress made over the initial aim to model certain components of blockchain and bitcoin (a blockchain-based protocol) using the Alloy tool. Some conclusions are drawn followed by a prospect of future work on what can be done further as follow up to the work reported in this dissertation. 6.1 Conclusions In the rapidly evolving field of computer engineering, the development of reliable and robust (very often safety-critical) software systems is paramount. Formal methods, a set of mathematical techniques used for specifying, designing, and verifying software systems, play a crucial role in ensuring the integrity and correctness of these systems. Furthermore, formal methods contribute significantly to the design phase of software development. By utilizing formal specification languages such as Alloy, one can model the system’s architecture and behavior, allowing for a systematic anticipation and exploration of possible scenarios. This modeling process assists in identifying potential design flaws early in the development lifecycle, reducing the likelihood of critical errors and enhancing the overall reliability of the system. Verification and validation are crucial aspects of software engineering, and formal methods excel in providing rigorous techniques for ensuring the correctness of software systems. Model checking is an attractive formal verification method used to mathematically challenge the correctness of a system with respect to its specification. This helps in identifying and eliminating errors before the software is implemented and deployed, minimizing the risk of system failures, security vulnerabilities, and costly post-release bug fixes. This dissertation explores the applicability of formal verification and model checking — formal method sub-disciplines — using the Alloy tool in a particular case study: to describe blockchain-based components. Chapter 3of this dissertation delves into the utilization of Alloy, a formal specification language, to 82 intricately describe the structure of a blockchain, encompassing blocks, cryptographic hashes, nonces and data (further details can be found in chapter 4). The incorporation of model checking within this context is of paramount importance, offering a robust methodology for ensuring the accuracy, consistency and reliability of the blockchain protocol model. Model checking, as a formal verification technique, plays a pivotal role in scrutinizing the specified properties of the blockchain protocol. By leveraging Alloy’s capabilities for expressing system properties and constraints, model checking facilitates the exploration of potentially critical scenarios within the blockchain protocol. This process aids in uncovering possible design flaws, verifying the correctness of cryptographic operations, and ensuring that the model aligns precisely with the intended behavior of a blockchain system. The rigorous analysis provided by model checking serves as a safeguard against critical errors that could compromise the integrity and security of the blockchain. Similarly, Chapter 4employs Alloy to meticulously delineate the intricate data structures of the Bitcoin (and other cryptocurrencies) blockchain. This encompasses the representation of blocks and transactions, incorporating essential elements such as Merkle roots, inputs, outputs with addresses, and transaction values. The inclusion of such elements adds layers of complexity to the Bitcoin blockchain model. Model checking proves instrumental in systematically validating the protocol’s ability to handle these intricacies, ensuring that the specified properties concerning transaction validity and data consistency are upheld throughout the modeled blockchain. It should be noted that Alloy (as model checking in general) does not guarantee that the system is correct in absolute terms, but it does give designers much confidence to move forward in the modelling process by presenting instances that correctly translate the technology to be modeled. Finally, Chapter 5introduces formal specifications on HD wallets. Model checking is indispensable when modeling the intricate structures of HD wallets, especially in the context of cryptocurrency, where the security of funds relies on the integrity of wallet management. The hierarchical nature of HD wallets introduces complexity, with master keys generating derived keys and addresses. Once again, Alloy proves instrumental in systematically validating the wallet’s ability to manage this hierarchy securely, upholding specified properties related to key derivation, privacy, and address uniqueness throughout the modeled HD wallet structure. In essence, the integration of model checking using the Alloy-analyser tool to model the blockchain protocol contributes significantly to the main dissertation’s objectives. It not only ensures the model adequately represents the intricacies of blockchain structures but also empowers to confidently assert the reliability and security of the designed protocol. Through the lens of model checking, this dissertation 83 provides a methodologically sound foundation for the subsequent analyses and discussions surrounding the blockchain’s formal representation and structural intricacies. 6.2 Prospect for future work The main purpose of this dissertation has been to lay the groundwork for modeling complex blockchain structures using Alloy. The journey can continue into the realm of practical implementations. Future work should pivot towards bridging the gap between abstract modeling and real-world application, thus transforming the Alloy-based insights into tangible, deployable solutions. A natural progression in extending the trajectory of this research lies in refining and expanding the existing Alloy-based models, transcending the confines of Bitcoin and extending the formal representations to encompass a spectrum of other cryptocurrencies. For instance, one avenue for further exploration involves modeling the intricate behavior of smart contracts within Ethereum, thereby broadening the application of Alloy to a diverse array of blockchain ecosystems. In particular, there are four main directions for future research, as explained below. 1. Enhanced and extended models. The enhancement and extension of the current Alloy models involve a nuanced approach to capturing the intricacies of blockchain structures. In the context of Bitcoin, this could encompass a more granular representation of transaction details, including additional script types, advanced multisignature schemes, and compatibility with emerging protocol upgrades. Moreover, the extension of models to cover other cryptocurrencies goes beyond a simple replication of the Bitcoin model. It involves meticulous consideration of the unique features and consensus mechanisms of each cryptocurrency, ensuring that the Alloy models are adaptable and applicable across a diverse array of decentralized systems. For Ethereum, this may involve capturing the complexities of smart contracts, such as their interaction with decentralized applications, execution environments and state transitions. 2. Transitioning from model to real-world implementation. The transition from Alloy models to real-world implementation is a pivotal phase where model checking plays a transformative role. This process involves the translation of the abstract concepts and relationships defined in the Alloy model into executable code. Model checking will serve as a quality assurance mechanism during this transition, validating that the implemented code faithfully reflects the properties and behaviors specified in the model. It acts as a safeguard against potential discrepancies, ensuring that the practical implementation aligns with the intended design and adheres to the formalized constraints of the Alloy model. This not only 84 instills confidence in the reliability of the implementation but also facilitates a smoother integration of formal methods into the real-world development workflow. 3. Leveraging model checking for practical insights. Model checking is not merely a means of verification; it is a powerful tool for gaining practical insights into the potential challenges and opportunities associated with real-world implementations. As developers traverse the path from model to code, model checking serves as a guide, revealing potential pitfalls, vulnerabilities, and performance bottlenecks that may arise during execution. By simulating various scenarios and conditions, developers can proactively address issues related to scalability, security, and system dynamics. This proactive stance is crucial for optimizing the practical implementation, as it allows for informed decision-making and strategic adjustments based on the insights gleaned from the model checking process. Thus, the true value of model checking is realized in its role as a dynamic and foresightful advisor throughout the practical implementation journey. 4. Integration of Merkle Trees. The integration of Merkle trees stands as a promising venture. These cryptographic structures, crucial for ensuring data integrity and efficiency in blockchain systems, can be seamlessly incorporated into Alloy models. This extension broadens the scope of the models, offering a comprehensive understanding of Merkle trees’ impact on blockchain systems and facilitating a deeper exploration of their role in decentralized ledger ecosystems. 85 Bibliography S. Aggarwal and N. Kumar. Chapter three - hashes. Adv. Comput. , 121:83–93, 2021a. doi: 10.1016/ BS.ADCOM.2020.08.003. URL https://doi.org/10.1016/bs.adcom.2020.08.003. S. Aggarwal and N. Kumar. Chapter four - digital signatures. Adv. Comput. , 121:95–107, 2021b. doi: 10. 1016/BS.ADCOM.2020.08.004. URL https://doi.org/10.1016/bs.adcom.2020.08.004. S. Aggarwal and N. Kumar. Chapter seven - basics of blockchain. Adv. Comput. , 121:129–146, 2021c. doi: 10.1016/BS.ADCOM.2020.08.007. URL https://doi.org/10.1016/bs.adcom.2020. 08.007. S. Aggarwal and N. Kumar. Chapter eight - history of blockchain-blockchain 1.0: Currency. Adv. Comput. , 121:147–169, 2021d. doi: 10.1016/BS.ADCOM.2020.08.008. URL https://doi.org/10. 1016/bs.adcom.2020.08.008. S. Aggarwal and N. Kumar. Chapter twenty-one - financial system. Adv. Comput. , 121:411–429, 2021e. doi: 10.1016/BS.ADCOM.2020.08.021. URL https://doi.org/10.1016/bs.adcom.2020. 08.021. S. Aggarwal and N. Kumar. Chapter twenty-two - transportation system. Adv. Comput. , 121:431–454, 2021f. doi: 10.1016/BS.ADCOM.2020.08.022. URL https://doi.org/10.1016/bs.adcom. 2020.08.022. A. Al-Mamun. Resource-efficient Blockchains for Reliable Data Management in Large-scale Distributed Systems . PhD thesis, University of Nevada, Reno, USA, 2023. URL http://hdl.handle.net/ 11714/8268. F. A. Aponte-Novoa, A. L. S. Orozco, R. Villanueva-Polanco, and P. Wightman. The 51 IEEE Access , 9: 140549–140564, 2021. doi: 10.1109/ACCESS.2021.3119291. B. Bernardo and D. Marmsoler. Front Matter, Table of Contents, Preface, Conference Organization. In Bruno Bernardo and Diego Marmsoler, editors, 3rd International Workshop on Formal Methods for 86 Blockchains (FMBC 2021) , volume 95 of Open Access Series in Informatics (OASIcs) , pages 0:i– 0:xii, Dagstuhl, Germany, 2021. Schloss Dagstuhl – Leibniz-Zentrum für Informatik. ISBN 978-3- 95977-209-9. doi: 10.4230/OASIcs.FMBC.2021.0. URL https://drops.dagstuhl.de/opus/ volltexte/2021/15424. C. E. Brown, C. Kaliszyk, T. Gauthier, and J. Urban. Proofgold: Blockchain for formal methods. In Z. Dargaye and C. Schneidewind, editors, 4th International Workshop on Formal Methods for Blockchains, FMBC@CAV 2022, August 11, 2022, Haifa, Israel , volume 105 of OASIcs , pages 4:1–4:15. Schloss Dagstuhl - Leibniz-Zentrum für Informatik, 2022. doi: 10.4230/OASICS.FMBC.2022.4. URL https: //doi.org/10.4230/OASIcs.FMBC.2022.4. B. Can, J. L. Hougaard, and M. Pourpouneh. On reward sharing in blockchain mining pools. Games and Economic Behavior , 136:274–298, 2022. ISSN 0899-8256. doi: https://doi.org/ 10.1016/j.geb.2022.10.002. URL https://www.sciencedirect.com/science/article/ pii/S0899825622001361. B. Carminati. Digital signatures. In Ling Liu and M. Tamer Özsu, editors, Encyclopedia of Database Systems, Second Edition . Springer, 2018. doi: 10.1007/978-1-4614-8265-9\_131. URL https: //doi.org/10.1007/978-1-4614-8265-9_131. D. C. Challener, M. E. Vachino, J. P. Howard II, C. K. Pikas, and A. John. Blockchain basics and suitability: A primer for program managers. J. Inf. Technol. Manag. , 30(3):33–44, 2019. URL https://jitm. ubalt.edu/XXX-3/article3.pdf. Y. Chen, Y. Chou, and Y. Chou. An image authentication scheme using merkle tree mechanisms. Future Internet , 11(7):149, 2019. doi: 10.3390/fi11070149. URL https://doi.org/10.3390/ fi11070149. L. Couto, J.N. Oliveira, M.A. Ferreira, and E. Bouwers. Preparing for a literature survey of software architecture using formal concept analysis, 2011. Proc. of the SQM’2011 workshop, colocated with CSMR 2011, Oldenburg, Germany. Z. Dargaye and C. Schneidewind. Front Matter, Table of Contents, Preface, Conference Organization. In Zaynah Dargaye and Clara Schneidewind, editors, 4th International Workshop on Formal Methods for Blockchains (FMBC 2022) , volume 105 of Open Access Series in Informatics (OASIcs) , pages 87 0:i–0:xii, Dagstuhl, Germany, 2022. Schloss Dagstuhl – Leibniz-Zentrum für Informatik. ISBN 978-3- 95977-250-1. doi: 10.4230/OASIcs.FMBC.2022.0. URL https://drops.dagstuhl.de/opus/ volltexte/2022/17181. P. Das, A. Erwig, S. Faust, J. Loss, and S. Riahi. Bip32-compatible threshold wallets. IACR Cryptol. ePrint Arch. , page 312, 2023. URL https://eprint.iacr.org/2023/312. S. Delgado-Segura, C. Pérez-Solà, G. Navarro-Arribas, and J. Herrera-Joancomartí. Analysis of the bitcoin UTXO set. IACR Cryptol. ePrint Arch. , page 1095, 2017. URL http://eprint.iacr.org/2017/ 1095. S. Delgado-Segura, S. Bakshi, C. Pérez-Solà, J. Litton, A. Pachulski, A. Miller, and B. Bhattacharjee. Txprobe: Discovering bitcoin’s network topology using orphan transactions. CoRR , abs/1812.00942, 2018. URL http://arxiv.org/abs/1812.00942. F. Franzoni and V. Daza. Sok: Network-level attacks on the bitcoin p2p network. IEEE Access , 10:94924– 94962, 2022. doi: 10.1109/ACCESS.2022.3204387. M.J. Gabbay, A. Jakobsson, and K. Sojakova. Money grows on (proof-)trees: The formal FA1.2 ledger standard. In B. Bernardo and D. Marmsoler, editors, 3rd Int. Workshop on FMBC (FMBC@CAV 2021) , volume 95 of OASIcs , pages 2:1–2:14. Schloss Dagstuhl - Leibniz-Zentrum für Informatik, 2021. doi: 10.4230/OASIcs.FMBC.2021.2. URL https://doi.org/10.4230/OASIcs.FMBC.2021.2. B. Ganter, G. Stumme, and R. Wille, editors. Formal Concept Analysis, Foundations and Applications , volume 3626 of LNCS , 2005. Springer-Verlag. ISBN 3-540-27891-5. G. Gutoski and D. Stebila. Hierarchical deterministic bitcoin wallets that tolerate key leakage. In Rainer Böhme and Tatsuaki Okamoto, editors, Financial Cryptography and Data Security - 19th International Conference, FC 2015, San Juan, Puerto Rico, January 26-30, 2015, Revised Selected Papers , volume 8975 of Lecture Notes in Computer Science , pages 497–504. Springer, 2015. doi: 10.1007/ 978-3-662-47854-7\_31. URL https://doi.org/10.1007/978-3-662-47854-7_31. S. Haber and W. S. Stornetta. How to time-stamp a digital document. J. Cryptol. , 3(2):99–111, 1991. doi: 10.1007/BF00196791. URL https://doi.org/10.1007/BF00196791. D. Jackson. Software Abstractions: Logic, Language, and Analysis . The MIT Press, Cambridge Mass., 2012. Revised edition, ISBN 0-262-01715-2. 88 A. Lochbihler and O. Marić. Authenticated Data Structures as Functors in Isabelle/HOL. In Bruno Bernardo and Diego Marmsoler, editors, 2nd Workshop on Formal Methods for Blockchains (FMBC 2020) , volume 84 of OpenAccess Series in Informatics (OASIcs) , pages 6:1–6:15, Dagstuhl, Germany, 2020. Schloss Dagstuhl–Leibniz-Zentrum für Informatik. ISBN 978-3-95977-169-6. doi: 10.4230/OASIcs. FMBC.2020.6. URL https://drops.dagstuhl.de/opus/volltexte/2020/13419. V. B. Mišić, J. Mišić, and X. Chang. On forks and fork characteristics in a bitcoin-like distribution network. In 2019 IEEE International Conference on Blockchain (Blockchain) , pages 212–219, 2019. doi: 10. 1109/Blockchain.2019.00035. K. Nagata, H. Kikuchi, and C. Fan. Risk of bitcoin addresses to be identified from features of output addresses. In 2018 IEEE Conference on Dependable and Secure Computing (DSC) , pages 1–6, 2018. doi: 10.1109/DESEC.2018.8625106. L. Nian and D. Chuen. Introduction to Bitcoin , pages 5–30. 12 2015. doi: 10.1016/B978-0-12-802117-0. 00001-1. E. Nowroozi, S. Seyedshoari, Y. Mekdad, E. Savas, and M. Conti. Cryptocurrency wallets: assessment and security. CoRR , abs/2303.12940, 2023. doi: 10.48550/ARXIV.2303.12940. URL https: //doi.org/10.48550/arXiv.2303.12940. J.N. Oliveira. Program Design by Calculation, 2019. Unpublished book draft, Feb. 2021. Informatics Dept., U.Minho (pdf). J.N. Oliveira and M.A. Ferreira. Alloy meets the algebra of programming: A case study. IEEE Trans. Soft. Eng. , 39(3):305–326, 2013. . R. M. Parizi, A. Dehghantanha, A. Azmoodeh, and K. R. Choo. Blockchain in cybersecurity realm: An overview. In Kim-Kwang Raymond Choo, Ali Dehghantanha, and Reza M. Parizi, editors, Blockchain Cybersecurity, Trust and Privacy , volume 79 of Advances in Information Security , pages 1–5. Springer, 2020. doi: 10.1007/978-3-030-38181-3\_1. URL https://doi.org/10.1007/ 978-3-030-38181-3_1. P. Raj. Chapter one - demystifying the blockchain technology. Adv. Comput. , 121:1–42, 2021. doi: 10. 1016/BS.ADCOM.2020.08.001. URL https://doi.org/10.1016/bs.adcom.2020.08.001. 89 M. Saad, M. T. Thai, and A. Mohaisen. Poster: Deterring ddos attacks on blockchain-based cryptocurrencies through mempool optimization. In Proceedings of the 2018 on Asia Conference on Computer and Communications Security , ASIACCS ’18, page 809–811, New York, NY, USA, 2018. Association for Computing Machinery. ISBN 9781450355766. doi: 10.1145/3196494.3201584. URL https://doi.org/10.1145/3196494.3201584. E. Sekerinski and N. Moreira et al , editors. Formal Methods. FM 2019 International Workshops - Porto, Portugal, October 7-11, 2019, Revised Selected Papers, Part I , volume 12232 of Lecture Notes in Computer Science , 2020. Springer. ISBN 978-3-030-54993-0. doi: 10.1007/978-3-030-54994-7. URL https://doi.org/10.1007/978-3-030-54994-7. Y. Shahsavari, K. Zhang, and C. Talhi. A theoretical model for fork analysis in the bitcoin network. In 2019 IEEE International Conference on Blockchain (Blockchain) , pages 237–244, 2019. doi: 10.1109/ Blockchain.2019.00038. Z. Wang, X. Dong, Y. Kang, and H. Chen. Parallel SHA-256 on SW26010 many-core processor for hashing of multiple messages. J. Supercomput. , 79(2):2332–2355, 2023. doi: 10.1007/S11227-022-04750-7. URL https://doi.org/10.1007/s11227-022-04750-7. J. Xu, W. Bai, M. Hu, H. Tian, and D. Wu. Bitcoin miners: Exploring a covert community in the bitcoin ecosystem. Peer-to-Peer Netw. Appl. , 14(2):644–654, 2021. doi: 10.1007/S12083-020-01021-1. URL https://doi.org/10.1007/s12083-020-01021-1. M. Zima. (short paper) inputs reduction for more space in bitcoin blocks. In 2018 Crypto Valley Conference on Blockchain Technology (CVCBT) , pages 112–115, 2018. doi: 10.1109/CVCBT.2018.00020. 90 Part I Appendices 91 ----------------------------- sig Block{ tx : one Tx, Next : lone Block } one sig BlockI extends Block{} sig Tx{ merkleRoot : one Word, -- merkle root transaction : set Transaction -- list of transactions } sig Word{} sig Transaction{ txid : one Word, -- hash of transaction fee : one Int, -- transaction fee paid to miner input : set Input, -- input set output : set Output -- output set } sig Input{ txid : one Word, -- hash of transaction feeding this input value : one Int, -- value in Satoshis sender : one BAddr -- address from the person who owns this inputs } sig Output{ value : one Int, -- value in Satoshis to : one BAddr -- address of the receiver } sig BAddr{} -------------------- -- Functions -------------------- -- Returns the inputs included in a set of blocks fun inputsFromBlocks[bs : set Block] : set Input {{i:Input | i in bs.tx.transaction.input}} -- Returns the unused hashes in Merkle roots and txid relations fun nonUsedHashesMrTxid : set Word {Word - Tx.merkleRoot-txFromBlocks[Block].txid 98 - inputsFromBlocks[afterSndBlock].txid} -- Returns all blocks succeeding the second block fun afterSndBlock : set Block {{x:Block | x in (BlockI.Next).^(Next)}} -- Returns the transactions included in a set of blocks fun txFromBlocks[bs : set Block] : set Transaction {{t:Transaction | t in bs.tx.transaction}} ------- -- Returns all inputs succeeding the second block fun inputAfterSndBlock : set Input {{i:confirmedInputs | i in afterSndBlock.tx.transaction.input}} -- Returns the transactions preceding the block containing a specific input fun precTxFromInput[i : one Input] : set Transaction {txFromBlocks[untilBlock[blockFromInput[i]]]} -- Returns the inputs associated with transactions fun confirmedInputs : set Input {Block.tx.transaction.input} -- Returns the block where an input is located fun blockFromInput[i:Input] : one Block {{b:Block | i in b.tx.transaction.input}} -- Returns all preceding blocks of a block b fun untilBlock[b:Block] : set Block {{x:Block | x in b.^(~Next)}} ------- -- Returns the sum of values from the outputs of a transaction fun sumOutputValues[t: Transaction]: Int {sum o: t.output | o.value} -- Returns the sum of values from the inputs of a transaction fun sumInputValues[t: Transaction]: Int {sum o: t.input | o.value} -- Returns the sum of values from the outputs plus the fee of a transaction fun sumOutputsValuesFee[t:Transaction] : Int {plus[sumOutputValues[t],t.fee]} -- Returns the transaction where an input was created fun originTx[i : one Input] : one Transaction {{t : Transaction | i.txid = t.txid}} 99 ------- utxos -- Returns the Unspent Transaction Outputs (UTXOs) of an address fun utxos[a : one BAddr] : set Output {{o : Output | o in (to.a - associatedOutput[sender.a])}} -- Auxiliary function for associatedOutput fun associatedOutputAux[i : one Input, t : one Transaction] : one Output {{o:Output | o in t.output and i.value = o.value and i.sender = o.to}} -- Returns the output associated with an input fun associatedOutput[i : one Input] : one Output {associatedOutputAux[i, originTx[i]]} -------------------- -- Predicates -------------------- -- 0.1. Injectivity of tx pred propInjectiveTx {tx.~tx in iden} -- 0.2. Injectivity of merkleRoot pred propInjectiveMerkleRoot {merkleRoot.~merkleRoot in iden} -- 0.3. Irreflexivity of Next pred propNoConfusionNext {no Next & iden} -- 0.4. Injectivity of Next pred propInjectiveNext {Next.~Next in iden } -- 0.5. Next should be acyclic pred propNoCycleChain {no ^Next & iden} -- 0.6. BlockI as first block pred propInitialBlockI {no Next.BlockI} -- 0.7. Reachability from BlockI pred propReachableFromBlockI 100 {all b : Block-BlockI | b in BlockI.^Next} -- -- -- 1. Non-empty transaction list pred propAtLeastOneTransaction {all t:Tx | some t.transaction} -- 2. Disjointness of merkleRoot and txid pred propDisjMerklerootTxid {no Tx.merkleRoot & Transaction.txid} -- 3. Injectivity of txid pred propInjectiveTxid {(Transaction<:txid).~(Transaction<:txid) in iden} -- 4. Injectivity of transaction pred propInjectiveTransaction {transaction.~transaction in iden} -- -- -- 5. Non-empty Input and Output sets pred propAtLeastOneInOneOut {all t : Transaction | some t.input and some t.output} -- 6. Injectivity of input pred propInjectiveInput {input.~input in iden} -- 7. No Input orphans pred propNoOrphanInputs {no Input - Block.tx.transaction.input} -- 8. No Output orphans pred propNoOrphanOutputs {no Output - Block.tx.transaction.output} -- -- -- 9. Disjointness of merkleRoot and txid pred propDisjMerklerootTxidInput {no Tx.merkleRoot & Input.txid} -- 10. A transaction must not feed itself pred propOrderedTxid {all tx : Tx | no tx.transaction.input.txid & tx.transaction.txid} 101 -- 11. Inputs from two beginning blocks pred propInputsFirst2Blocks {inputsFromBlocks[Block-afterSndBlock].txid in nonUsedHashesMrTxid} -- 12. Input/Transaction referencing pred propSequenceInput {all i:inputAfterSndBlock | one t: precTxFromInput[i] | i.txid = t.txid} -- -- -- 13. Transact positive values pred propPositiveValues {all iv:Input.value, ov:Output.value, f: Transaction.fee | iv>0 and ov>0 and f>0} -- 14. Input, output and fee balance pred propBalanceValues {all t:Transaction | sumInputValues[t] = sumOutputsValuesFee[t]} -- 15. Input/Output referencing pred propReferenceInputOutput {all i:inputAfterSndBlock | one o: originTx[i].output | i.value = o.value and i.sender = o.to} -- fact Facts{ -- From previous model -- tx Predicates -- 0.1. propInjectiveTx -- -- merkleRoot Predicates -- 0.2. propInjectiveMerkleRoot -- -- Next Predicates -- 0.3. propNoConfusionNext -- 0.4. propInjectiveNext 102 -- 0.5. propNoCycleChain -- 0.6. propInitialBlockI -- 0.7. propReachableFromBlock -- -- ------- -- 1. propAtLeastOneTransaction -- 2. propDisjMerklerootTxid -- 3. propInjectiveTxid -- 4. propInjectiveTransaction ------- ------- -- 5. propAtLeastOneInOneOut -- 6. propInjectiveInput -- 7. propNoOrphanInputs -- 8. propNoOrphanOutputs ------- ------- -- 9. propDisjMerklerootTxidInput -- 10. propOrderedTxid -- 11. propInputsFirst2Blocks -- 12. propSequenceInput ------- ------- -- 13. propPositiveValues 103 -- 14. propBalanceValues -- 15. propReferenceInputOutput ------- } ----------- -- Run ----------- run{ -- No orphan transactions no Transaction - Block.tx.transaction -- No orphan Tx no Tx - Block.tx -- No orphan addresses no BAddr - Block.tx.transaction.input.sender -- Each block has at most 1 transaction all b:Block | #b.tx.transaction < 2 -- Each transaction has at most 1 input all t:Transaction | #t.input < 2 -- Each transaction has at most 1 output all t:Transaction | #t.output < 2 } for 10 but exactly 4 Block A.3 HD wallets Alloy code ----------------------------- -- HD Wallets Structure ----------------------------- sig PrivateKey{ generates : one PublicKey -- public key } sig PublicKey{ addresses : one BAddr -- cryptocurrency address } sig BAddr{} 104 sig MasterPrivateKey{ creates : set PrivateKey, -- children private keys originates : set MasterPrivateKey, -- children master private keys determinates : one MasterPublicKey -- master public key } sig MasterPublicKey{ derives : set PublicKey -- public keys derived } -------------------- -- Functions -------------------- -- Returns orphaned master public keys fun orpahnMasterPublicKeys : set MasterPublicKey {{mpk : MasterPublicKey | mpk not in MasterPrivateKey.determinates}} -- Returns orphaned public keys fun orpahnPublicKeys : set PublicKey {{p : PublicKey | p not in PrivateKey.generates+MasterPublicKey.derives}} -- Returns all public keys originated from a master private key fun pubKeys[mpk : one MasterPrivateKey] : set PublicKey {{p : PublicKey | p in (mpk.creates.generates + mpk.^originates.creates.generates)}} -------------------- -- Predicates -------------------- -- 1. Injectivity of generates pred propInjectiveGenerates {generates.~generates in iden} -- 2. Injectivity of addresses pred propInjectiveAddresses {addresses.~addresses in iden} -- 3. Injectivity of creates pred propInjectiveCreates {creates.~creates in iden} 105 -- 4. Injectivity of originates pred propInjectiveOriginate {originates.~originates in iden} -- 5. Relation originates should be acyclic pred propNoCycleOriginates {no ^originates & iden} -- 6. Injectivity of determinates pred propInjectiveDeterminates {determinates.~determinates in iden} -- 7. Master public key/Public keys reference pred propCycledChainMPK {all mpk : MasterPrivateKey | mpk.determinates.derives = pubKeys[mpk]} -- 8. A master private key creates at least -- one private key or one master private key pred propAtLeastOneCreatesOrOneOriginates {all mpk : MasterPrivateKey | some mpk.creates or some mpk.originates} -- 9. At least one master private key pred propAtLeastOneMasterPrivateKey {some MasterPrivateKey} -- 10. No orphaned Master Public Keys pred propNoOrpahnMasterPublicKeys {no orpahnMasterPublicKeys} -- 11. No orphaned Public Keys pred propNoOrpahnPublicKeys {no orpahnPublicKeys} fact Facts{ -- 1. propInjectiveGenerates 106 -- 2. propInjectiveAddresses -- 3. propInjectiveCreates -- 4. propInjectiveOriginate -- 5. propNoCycleOriginates -- 6. propInjectiveDeterminates -- 7. propCycledChainMPK -- 8. propAtLeastOneCreatesOrOneOriginates -- 9. propAtLeastOneMasterPrivateKey -- 10. propNoOrpahnMasterPublicKeys -- 11. propNoOrpahnPublicKeys } ----------- -- Run ----------- run{ one mpk : MasterPrivateKey | #mpk.originates = 1 and #mpk.creates = 1 } for 20 107