Solutions

Company

Resources

Blog

Contact

Login

    • Assurance

      Smart Contract Assessment

      Securing code integrity, protecting digital assets

      Blockchain Layer 1 Assessment

      Assessing protocols, securing blockchain foundations

      Code Security Audit

      Uncovering flaws, strengthening software integrity

      Web Application Penetration Testing

      Exposing weaknesses, fortifying digital defenses

      Cloud Infrastructure Penetration Testing

      Securing configurations, protecting critical environments

      Red Team Exercise

      Simulating real-world attacks, strengthening defenses

      AI Red Teaming

      Testing AI systems against real threats

      AI Security Assessment

      Securing AI models, data, and pipelines

    • Advisory

      AI Advisory

      Guiding secure, strategic AI adoption forward

      Risk Assessment

      From unknown threats to actionable insights

      Blockchain Architecture Assessment

      Optimizing architecture for tomorrow’s networks

      Compliance Readiness

      Stay ready as regulations evolve

      Custody and Key Management Assessment

      Securing the heart of digital custody

      Technical Due Diligence

      See the risks before you invest

      Technical Training

      Empower your teams to secure what matters

    • Who We Are

      The best security engineers in the world

      Careers

      Work with the elite

      Who Trusts Us

      The trusted security advisor for blockchain and financial services industries

      Brand

      Access official logos, fonts, and guidelines

      Service Commitments

      Committed to Protecting Your Data

    • Audits

      In-depth evaluations of smart contracts and blockchain infrastructures

      BVSS

      Blockchain Vulnerability Scoring System

      Disclosures

      All the latest vulnerabilities discovered by Halborn

      Case Studies

      How Halborn’s solutions have empowered clients to overcome security issues

      Reports

      Comprehensive reports and data

  • Blog

  • Contact

  • Login

THIS WEBSITE USES COOKIES

We use cookies to personalise content and ads, to provide social media features and to analyse our traffic. We also share information about your use of our site with our social media, advertising and analytics partners who may combine it with other information that you've provided to them or that they've collected from your use of their services. You consent to our cookies if you continue to use our website. Learn More.

STAY CURRENT WITH HALBORN

Subscribe to the monthly Halborn Digest for our top blogs and videos, major company announcements, new whitepapers, webinar and event invites, and one exclusive interview.

ADVISORY SERVICES

AI AdvisoryRisk AssessmentBlockchain Architecture AssessmentCompliance ReadinessCustody and Key Management AssessmentTechnical Due DiligenceTechnical Training

ASSURANCE SERVICES

AI Security AssessmentAI Red TeamingSmart Contract AssessmentBlockchain Layer 1 AssessmentCode Security AuditWeb Application Penetration TestingCloud Infrastructure Penetration TestingRed Team Exercise

COMPANY

Who We AreWho Trusts UsService CommitmentsCareersBrandBlogContact

RESOURCES

AuditsDisclosuresReportsBVSSCase Studies
Halborn Logo
Privacy PolicyTerms of UseVulnerability Disclosure Policy

© Halborn 2025. All rights reserved.

Background

// Security Assessment

06.30.2025 - 08.01.2025

Nano Contracts

Hathor Labs (Hathor Network)

Halborn logotext
← Back to Audits

Nano Contracts - Hathor Labs (Hathor Network)


Prepared by:

Halborn Logo

HALBORN

Last Updated 11/07/2025

Date of Engagement: June 30th, 2025 - August 1st, 2025

Summary

100% of all REPORTED Findings have been addressed

All findings

21

Critical

0

High

0

Medium

4

Low

1

Informational

16


Table of Contents

  • 1. Introduction
  • 2. Assessment summary
  • 3. Protocol overview
  • 4. Scope of audit
  • 5. Advanced security analysis
    • 5.1 Python sandbox security analysis
    • 5.2 Custom test development
  • 6. Tool-assisted analysis
    • 6.1 Automated static analysis
  • 7. Assessment methodology
    • 7.1 Manual code review process
    • 7.2 Tool-assisted analysis
  • 8. Test coverage and methodology
  • 9. Critical security context
  • 10. Executive summary
  • 11. Detailed assessment coverage
  • 12. Serialization
    • 12.1 Core serialization components
    • 12.2 Serialization security analysis
    • 12.3 Serialization security analysis
  • 13. Transaction processing
    • 13.1 Transaction header analysis
    • 13.2 Transaction validation deep dive
    • 13.3 Transaction storage and state management
  • 14. Nano contracts core
    • 14.1 Execution engine deep analysis
    • 14.2 Blueprint system analysis
    • 14.3 Storage system deep dive
    • 14.4 On-chain blueprint analysis
    • 14.5 Context management analysis
    • 14.6 Method system analysis
    • 14.7 Custom builtins analysis
  • 15. Verification & validation
    • 15.1 Ast-based code validation
    • 15.2 Transaction verification
    • 15.3 Nano header verification
  • 16. Storage & indexes
    • 16.1 Contract storage analysis
    • 16.2 Patricia trie implementation
    • 16.3 Block storage analysis
    • 16.4 Changes tracker analysis
    • 16.5 Index management
  • 17. Consensus integration
    • 17.1 Consensus algorithm integration
    • 17.2 Consensus settings
  • 18. Access control & permissions
    • 18.1 Syscall restrictions
    • 18.2 Method visibility and access control
    • 18.3 Context isolation
  • 19. Risk methodology
  • 20. Scope
  • 21. Assessment summary & findings overview
  • 22. Findings & Tech Details
    1. 22.1 Deterministic random number generation
    2. 22.2 Invalid custom builtins mapping
    3. 22.3 Incorrect bounds calculation in sized integers
    4. 22.4 Weak hash function in trie node calculation
    5. 22.5 Double proxy call bypasses blueprint validation
    6. 22.6 Incomplete method parameter validation
    7. 22.7 Missing timestamp type validation
    8. 22.8 Incomplete deserialization validation
    9. 22.9 Missing cache management in single value fields
    10. 22.10 Missing context immutability enforcement
    11. 22.11 Missing ast compiler stack depth protection
    12. 22.12 Missing resource metering in execution engine
    13. 22.13 Inadequate input validation in script execution
    14. 22.14 Inefficient type checking with typo
    15. 22.15 Incomplete changes tracker reset
    16. 22.16 Non-sequential transaction allowance
    17. 22.17 Union type handling issues
    18. 22.18 Missing collection type support
    19. 22.19 Missing blueprint syntax validation integration
    20. 22.20 Missing action amount validation
    21. 22.21 Missing token whitelist validation

1. Introduction


Hathor Labs engaged our security analysis team to conduct a comprehensive security assessment of Hathor Labs' nanocontracts smart contract ecosystem. The primary objective was to thoroughly evaluate the security architecture of the nanocontracts module to identify vulnerabilities, assess existing security measures, and provide actionable recommendations to enhance both the security and operational effectiveness of their smart contract framework. Our assessment was strictly limited to the provided nanocontracts codebase, ensuring a focused and exhaustive analysis of their security features.

2. Assessment Summary

Our engagement with Hathor Labs spanned a 25-day period (June 30, 2025 to August 1, 2025), during which we assigned a full-time security engineer with extensive experience in blockchain security, advanced penetration testing skills, and deep knowledge of various blockchain protocols. The objectives of this assessment were to:

    • Verify the correct functionality of the nanocontracts operations and execution engine

    • Identify potential security vulnerabilities within the nanocontracts system

    • Assess the integration between nanocontracts and the Hathor blockchain consensus

    • Provide recommendations to improve the security and efficiency of the nanocontracts framework

3. Protocol Overview

Hathor Core is a Layer 1 blockchain implementing a Directed Acyclic Graph (DAG) architecture that supports both transaction and block vertices. The nanocontracts module provides smart contract functionality with a Python-based execution engine, enabling developers to create decentralized applications (dApps) on the Hathor network.


Key Architecture Components:

    • DAG-based Consensus: Supports both native HTR tokens and custom tokens

    • Nanocontracts Engine: Python-based smart contract execution with blueprint system

    • State Management: Patricia trie-based storage with Merkle tree implementation

    • Transaction Processing: Integrated validation and consensus mechanisms

    • Version: 0.64.0 (current codebase version)

4. Scope of Audit

In-Scope Components:

    • Primary Module: hathor/nanocontracts/ directory

    • Code Coverage: 73 Python files, approximately 12,494 lines of code

    • Key Modules Reviewed:

Category

Description

Critical Components

Serialization

Data encoding/decoding and storage formats

Type system, encoding adapters, Patricia trie

Transaction Processing

Transaction validation, consensus, and execution flow

Runner engine, method execution, syscall validation

Nano Contracts Core

Contract execution engine and runtime

Blueprint system, context management, storage

Verification & Validation

Security checks and validation logic

AST analysis, signature verification, action validation

Storage & Indexes

Data persistence and querying

Contract storage, balance management, state consistency

Consensus Integration

How nanocontracts integrate with blockchain consensus

Transaction processing, state updates, reorg handling

Access Control & Permissions

Authorization and permission systems

Syscall restrictions, method visibility, authority control

Out of Scope:

    • Resource Management: Memory limits, CPU limits, and gas mechanisms were intentionally excluded due to identified critical issues that would have resulted in denial-of-service vulnerabilities

    • Network Layer: P2P communication and network protocol security

    • Wallet Implementation: Private key management and wallet security

    • External Dependencies: Third-party libraries and dependencies

5. Advanced Security Analysis

5.1 Python Sandbox Security Analysis


The advanced security analysis focused on the Python sandbox environment and its security mechanisms, particularly examining potential attack vectors around reflection-based patterns and sandbox bypass techniques. Our analysis examined the complete sandbox implementation and tested theoretical escape vectors to validate the effectiveness of the security controls protecting the nanocontracts environment.


Custom Test Development:


Our custom test development included comprehensive reflection-based escape analysis that tested Python reflection capabilities extensively. Built-in function analysis provided detailed examination of available built-in functions and their security implications, while object introspection testing analyzed object introspection and class traversal capabilities. Sandbox bypass attempts testing covered various theoretical bypass techniques to validate the effectiveness of the security controls.


Sandbox Security Findings:


The sandbox security analysis examined potential attack vectors that could theoretically compromise the Python execution environment. Our analysis tested reflection-based attack patterns including __class__, __subclasses__(), and __globals__ access patterns that would typically be used to bypass security controls in unprotected Python environments. Testing of built-in function access through class traversal mechanisms and SafeObject wrapper bypass techniques was conducted as part of our comprehensive security methodology.


Important Note: These attack vectors are effectively mitigated by the AST-based validation implemented in the _RestrictionsVisitor, which blocks any code containing double underscores (__) before execution. The AST validation serves as a robust defense mechanism that prevents these reflection-based attacks from being executed in the nanocontracts environment.

5.2 Custom Test Development


Test Coverage Analysis:


Our comprehensive test development included type system testing with comprehensive coverage of all NC types with edge cases, serialization testing with malformed data scenarios, and context manipulation testing to validate context object security. Method invocation testing examined method invocation with invalid parameters, while storage manipulation testing covered storage state manipulation and corruption scenarios. Trie integrity testing validated Patricia trie integrity and manipulation resistance.


Custom Test Scripts Developed:


The custom test development process created specialized test scripts for type system edge cases with boundary conditions, serialization fuzzing with malformed and edge case data, and context manipulation tests for context object modification and manipulation. Method parameter validation tests examined method invocation with invalid parameters, while storage state corruption tests covered storage state manipulation scenarios. Trie manipulation tests validated Patricia trie integrity, while execution limits tests examined execution engine limits and security boundaries.

6. Tool-Assisted Analysis

6.1 Automated Static Analysis


The tool-assisted analysis employed both automated and custom tools to ensure comprehensive coverage of the nanocontracts codebase. Our approach combined automated static analysis with custom tool development to identify security issues and validate code quality.


Semgrep Custom Rules:


Our Semgrep custom rules implementation included comprehensive patterns for detecting various security issues. Type validation patterns were developed to detect missing type validation throughout the codebase, while bounds checking patterns identified missing bounds checking in critical areas. Error handling patterns were designed to detect missing error handling, while security control patterns identified potential security control bypasses. Resource management patterns were developed to detect resource management issues that could lead to denial of service or other security problems.


Custom Static Analysis:


The custom static analysis tools provided specialized capabilities for detecting security issues. AST-based analysis tools were developed for detecting dangerous code patterns in Python code, while type system analysis tools examined type system completeness and correctness. Serialization analysis tools analyzed serialization security and integrity, while storage analysis tools examined storage security and consistency. Execution analysis tools were developed to analyze execution engine security and limits.

7. Assessment Methodology

7.1 Manual Code Review Process


The assessment methodology employed a comprehensive approach combining manual code review with automated analysis tools. Our methodology ensured thorough coverage of all nanocontracts components while maintaining the highest standards of security analysis.


Review Methodology:


The manual code review process included line-by-line analysis of all 12,494 lines of nanocontracts code, ensuring complete coverage of the codebase. Cross-reference analysis was performed between related components to understand integration points and dependencies. Dependency analysis examined external library usage and potential security implications, while integration analysis focused on the interaction points between different system components.


Security boundary analysis examined the security boundaries and access controls throughout the system, while edge case identification focused on identifying boundary conditions and potential vulnerabilities. This comprehensive approach ensured that no aspect of the codebase was overlooked during the security assessment.


Review Documentation:


The review documentation process included comprehensive notes for each file and component reviewed, ensuring that all findings were properly documented and tracked. Issue tracking provided detailed tracking of all identified issues and concerns, while test case development focused on creating custom test cases for validation of identified issues.


Proof-of-concept development was undertaken for critical vulnerabilities to demonstrate their potential impact, while recommendation development focused on creating detailed security recommendations for addressing identified issues. This documentation process ensured that all findings were properly communicated and actionable.

7.2 Tool-Assisted Analysis

Automated Tools Used:

Our automated tool analysis employed Semgrep with custom rules for detecting security issues and patterns, custom static analysis tools for AST analysis and code pattern detection, and fuzzing tools for input validation testing. Code coverage tools ensured comprehensive code coverage, while performance analysis tools analyzed resource consumption and limits.

Custom Tool Development:

The custom tool development process created specialized tools including AST analysis tools for analyzing Python AST for security issues, type system analysis tools for examining type system completeness, and serialization analysis tools for analyzing serialization security. Storage analysis tools examined storage security and consistency, while execution analysis tools analyzed execution engine security and limits.

8. Test Coverage and Methodology

In addition to manual and automated review, we leveraged code coverage analysis tools to measure the effectiveness of both the original and custom test suites. This allowed us to identify and address any untested code paths or edge cases, ensuring that the assessment provided comprehensive coverage of the nanocontracts codebase. Where coverage gaps were identified, we developed targeted tests and performed focused manual review to ensure no critical logic was left unexamined.

9. Critical Security Context

During the audit period, the Hathor Labs team identified and addressed a critical security issue related to mutable context sharing in the nanocontracts environment. This issue involved the potential for malicious contracts to override exposed mutable functions/objects (such as RNG functions) in the shared context, which could cause other contracts to use the compromised implementation. This finding was resolved by the development team before the completion of our audit and is not included in our vulnerability assessment.

10. Executive Summary

This security assessment of Hathor Labs' nanocontracts ecosystem provides a comprehensive evaluation of the smart contract framework's security posture. By addressing the identified issues and implementing the recommended improvements, Hathor Labs can significantly enhance the security, reliability, and trustworthiness of their nanocontracts platform.

The audit revealed several areas where security controls can be strengthened, particularly in the areas of input validation, state management, and execution environment isolation. Our recommendations focus on both immediate security improvements and long-term architectural enhancements to ensure the robustness of the nanocontracts ecosystem.

11. Detailed Assessment Coverage

12. Serialization

12.1 Core Serialization Components


The serialization system forms the foundational layer of the nanocontracts type safety and data integrity mechanisms. The comprehensive type system provides serialization adapters for all supported data types, ensuring proper validation, bounds checking, and format verification across the entire nanocontracts ecosystem.


hathor/serialization/compound_encoding/signed_data.py

The SignedData wrapper provides cryptographic integrity for serialized data structures through a generic type-safe implementation. This wrapper maintains type safety across serialization boundaries while providing script input validation and signature verification capabilities. The implementation ensures that all serialized data maintains cryptographic integrity through proper signature validation and type checking mechanisms.


hathor/nanocontracts/nc_types/ (Complete Type System Analysis)

The nanocontracts type system represents a comprehensive framework for handling all supported data types with proper serialization adapters. The complete type system architecture was examined, covering how each NC type implements serialization and deserialization with proper error handling, bounds checking, and format validation. The type system provides custom validators for each data type, ensuring that all serialized data maintains integrity and type safety throughout the system.


Key Files Reviewed:

The type system analysis encompassed eighteen core files, each implementing specific serialization patterns and validation logic. The address_nc_type.py file implements address format validation with strict 20-byte length enforcement, ensuring all addresses conform to the required cryptographic format. Boolean serialization in bool_nc_type.py provides strict 0/1 validation, preventing any ambiguous boolean representations.


Variable-length byte serialization in bytes_nc_type.py implements length prefixing mechanisms, while collection_nc_type.py handles complex data structures including lists, sets, deques, and frozensets with recursive type checking capabilities. The dataclass_nc_type.py implementation provides field-by-field validation for structured data, while fixed_size_bytes_nc_type.py enforces strict size constraints for byte arrays.


Dictionary serialization in map_nc_type.py includes comprehensive key-value pair validation, while namedtuple_nc_type.py preserves field names and types during serialization. The base type system in nc_type.py provides common serialization patterns used throughout the system, while null_nc_type.py handles null value processing for optional types.


Optional type support in optional_nc_type.py provides null value support through wrapper implementations, while signed_data_nc_type.py implements cryptographically signed data serialization with proper signature validation. Fixed-size integer serialization in sized_int_nc_type.py includes comprehensive bounds checking, while str_nc_type.py provides UTF-8 encoding with appropriate length limits.


Token UID serialization in token_uid_nc_type.py includes native token handling capabilities, while tuple_nc_type.py supports both fixed and variable-length tuple serialization patterns. Variable-length integer serialization in varint_nc_type.py implements LEB128 encoding for efficient integer representation, and utils.py provides essential type system utilities and helper functions.


hathor/nanocontracts/storage/patricia_trie.py

The Patricia trie implementation serves as the core state storage mechanism, providing a Merkle tree-based approach to data persistence. The detailed implementation of node ID calculation and propagation mechanisms was examined, reviewing how changes propagate from leaves to root with proper ID updates. The hash function usage analysis revealed the employment of SHA1 for node ID calculation, which has significant security implications for the overall system integrity.

12.2 Serialization Security Analysis


Type System Vulnerabilities Identified:

The comprehensive examination of the type system revealed several areas of concern in the serialization mechanisms. The unbounded deserialization possibility in VarInt types occurs when the _max_byte_size parameter is set to None, removing upper bounds on integer values and allowing arbitrary large integers that could potentially cause memory exhaustion, CPU exhaustion during arithmetic operations, and integer overflow in calculations.


The missing type validation in AddressNCType represents a potential security gap, as the implementation only performs length checking without validating address format or checksum. This allows invalid address bytes to pass length validation while failing cryptographic validation downstream, potentially bypassing address-based security checks.


A bounds calculation concern exists in SizedIntNCType where the _lower_bound_value calculation incorrectly uses -(2**self._byte_size) instead of the correct -2**(self._byte_size * 8 - 1) formula. This results in invalid lower bound values that cause serialization issues for valid data, particularly affecting Int32 types where the minimum value should be -(2**32//2) but is currently limited to -16.


The weak hash function usage in trie node ID calculation represents a fundamental security concern, as SHA1 is considered cryptographically broken for security purposes. This could lead to hash collisions and potential trie corruption, compromising the integrity of the entire state storage system.


Type System Implementation Notes:

The type system implementation revealed several design decisions and potential areas of concern. The FIELD_TYPE_TO_NC_TYPE_MAP mapping shows how built-in types are mapped to NC types, with specific handling for mutable types:

DEFAULT_TYPE_ALIAS_MAP: TypeAliasMap = {
    **ESSENTIAL_TYPE_ALIAS_MAP,
    OrderedDict: dict,
    bytearray: bytes,
    list: tuple,  # Mutable list converted to immutable tuple
    set: frozenset,  # Mutable set converted to immutable frozenset
}

This mapping ensures that mutable types are automatically converted to immutable variants, but the conversion process could potentially be exploited if not properly validated. The make_nc_type_for_field_type function uses this mapping to create NC types for field annotations, while make_nc_type_for_arg_type and make_nc_type_for_return_type use different mappings for function parameters and return values.


Type System Edge Cases:


The examination of various edge cases in the type system included the handling of Union types and type aliases. The ESSENTIAL_TYPE_ALIAS_MAP shows how Union types are handled:

ESSENTIAL_TYPE_ALIAS_MAP: TypeAliasMap = {
    Union: UnionType,  # type: ignore[dict-item]
}

The examination revealed potential issues with Union type handling, particularly when Python collapses Union types with the same type. For example, Union[int, int] becomes just int, which could lead to unexpected behavior in type validation.


Type System Testing Examples:


The comprehensive testing of the type system included various edge cases and boundary conditions:

# Fixed-size bytes testing
>>> make_nc_type_for_arg_type(VertexId).from_bytes(b'1111111111111111111111111111111')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "hathor-core/hathor/nanocontracts/nc_types/nc_type.py", line 139, in from_bytes
    value = self.deserialize(deserializer)
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "hathor-core/hathor/nanocontracts/nc_types/nc_type.py", line 122, in deserialize
    value = self._deserialize(deserializer)
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "hathor-core/hathor/nanocontracts/nc_types/fixed_size_bytes_nc_type.py", line 70, in _deserialize
    return self._filter_out(bytes(deserializer.read_bytes(self._size)))
                                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "hathor-core/hathor/serialization/bytes_deserializer.py", line 66, in read_bytes
    b = self.peek_bytes(n, exact=exact)
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "hathor-core/hathor/serialization/bytes_deserializer.py", line 55, in peek_bytes
    raise OutOfDataError('not enough bytes to read')
hathor.serialization.exceptions.OutOfDataError: not enough bytes to read

This testing revealed that the serialization system properly handles insufficient data scenarios, but the error handling could potentially be improved for better debugging and recovery.

Collection Type Analysis:


The examination of collection types revealed specific handling for different data structures:

# List of lists are not supported as the types are in 
arg_type
but not on
field_type
# SetNCType has a different logic # SetNCType._is_hashable does return false, so
set[set]
is not allowed

The collection type system implements specific restrictions to prevent problematic nested structures, but these restrictions could potentially be bypassed through careful manipulation of the type system.


Serialization Edge Cases Tested:


The testing methodology included comprehensive edge case analysis to validate the robustness of the serialization system. Empty byte array handling was verified to ensure proper processing of zero-length byte arrays without causing serialization errors. Maximum length string testing validated that string serialization properly enforces length limits and handles boundary conditions appropriately.


Nested collection analysis examined recursive type checking in complex scenarios such as list-of-lists and set-of-sets, ensuring that the type system properly handles deeply nested data structures. Optional type handling verification confirmed proper null value processing for optional types, while tuple interpretation testing identified potential confusion between fixed and variable-length tuple serialization patterns.


Tuple Serialization Analysis:


The examination of tuple serialization revealed potential interpretation issues:

>>> make_nc_type_for_return_type(tuple[int,int,int,int,int]).from_bytes(b'\x04\x01\x01\x01\x01')
(4, 1, 1, 1, 1)
>>> make_nc_type_for_return_type(tuple[int,Ellipsis]).from_bytes(b'\x04\x01\x01\x01\x01')
(1, 1, 1, 1)

This demonstrates that the same byte sequence can be interpreted differently depending on the tuple type definition, which could potentially lead to data corruption or security issues if not properly validated.


hathor/nanocontracts/storage/patricia_trie.py

The Patricia trie implementation serves as the core state storage mechanism, providing a Merkle tree-based approach to data persistence. The detailed examination of the Patricia trie used for state storage covered how node IDs are calculated and propagated through the trie structure. Hash function usage analysis examined the use of SHA1 for node ID calculation and its security implications, while trie integrity mechanisms review covered how changes propagate from leaves to root with proper ID updates.

12.3 Serialization Security Analysis


Type System Vulnerabilities Identified:


The comprehensive examination of the type system revealed several areas of concern in the serialization mechanisms. The unbounded deserialization possibility in VarInt types occurs when the _max_byte_size parameter is set to None, removing upper bounds on integer values and allowing arbitrary large integers that could potentially cause memory exhaustion, CPU exhaustion during arithmetic operations, and integer overflow in calculations.


The missing type validation in AddressNCType represents a potential security gap, as the implementation only performs length checking without validating address format or checksum. This allows invalid address bytes to pass length validation while failing cryptographic validation downstream, potentially bypassing address-based security checks.


A bounds calculation concern exists in SizedIntNCType where the _lower_bound_value calculation incorrectly uses -(2**self._byte_size) instead of the correct -2**(self._byte_size * 8 - 1) formula. This results in invalid lower bound values that cause serialization issues for valid data, particularly affecting Int32 types where the minimum value should be -(2**32//2) but is currently limited to -16.


The weak hash function usage in trie node ID calculation represents a fundamental security concern, as SHA1 is considered cryptographically broken for security purposes. This could lead to hash collisions and potential trie corruption, compromising the integrity of the entire state storage system.


Serialization Edge Cases Tested:


The testing methodology included comprehensive edge case analysis to validate the robustness of the serialization system. Empty byte array handling was verified to ensure proper processing of zero-length byte arrays without causing serialization errors. Maximum length string testing validated that string serialization properly enforces length limits and handles boundary conditions appropriately.


Nested collection analysis examined recursive type checking in complex scenarios such as list-of-lists and set-of-sets, ensuring that the type system properly handles deeply nested data structures. Optional type handling verification confirmed proper null value processing for optional types, while tuple interpretation testing identified potential confusion between fixed and variable-length tuple serialization patterns.

13. Transaction Processing

13.1 Transaction Header Analysis


The transaction processing system represents the core mechanism through which nanocontracts interact with the Hathor blockchain. The examination focused on the comprehensive transaction header structure and the associated validation mechanisms that ensure transaction integrity and proper contract execution.


hathor/transaction/headers/nano_header.py

The NanoHeader structure serves as the primary container for contract execution metadata, providing the necessary information for transaction validation and contract execution. The comprehensive examination of the nano header structure covered contract execution metadata, reviewing how nano actions are encoded and decoded in transaction headers. The script execution context analysis revealed how script data is embedded and executed within transaction context, while contract ID derivation logic was examined to understand the difference between deriving contract IDs from transaction hashes versus using explicit contract IDs.


Nano Header Buffer Analysis:

The examination of nano header buffer generation revealed insights into the transaction serialization process. The header structure includes multiple components that must be properly validated:

def serialize_action(type: int, token_index: int, amount: int) -> bytes:
    type_bytes = struct.pack('!B', type)  # Single byte type
    ret = [
        type_bytes,
        int_to_bytes(token_index, 1),
        output_value_to_bytes(amount),
    ]
    return b''.join(ret)

This serialization function demonstrates how actions are encoded in transaction headers, with type, token index, and amount being packed into a byte sequence. The examination covered potential areas of concern in the buffer handling, particularly around integer overflow in the int_to_bytes function and the output_value_to_bytes conversion.


Header Deserialization Testing:


The examination included comprehensive testing of header deserialization:

header = NanoHeader.deserialize(
    Transaction(),
    VertexHeaderId.NANO_HEADER.value +
    b'\x11'*32 +
    b'\xb9\x60' +
    b'\x0ainitialize' +
    b'\x00\x01' + # args bytes len
    b'\xff' +
    b'\x01' + # action len
    serialize_action(
        type=1,
        token_index=1,
        amount=1
    ) +
    b'\xaa' + b'\xbb' * 24 + # Total 25
    b'\x01' + # Script len
    b'\xff',
verbose=lambda k,v: print(f"{k}: {v}"))

This testing revealed the complex structure of nano headers and the potential for buffer manipulation or overflow attacks if not properly validated.


Transaction Processing Notes:


The examination of transaction processing analyzed the verification and validation mechanisms for completeness and security. The NanoHeaderVerifier implementation was examined for its handling of empty scripts (nc_script_len = 0) to understand signature verification requirements. The action validation logic in verify_action_list was analyzed for business logic restrictions that prevent simultaneous deposit and withdrawal on the same token, confirming proper validation controls.


The sequence number handling in block storage was examined for its allowance of non-sequential transactions with MAX_SEQNUM_JUMP_SIZE limits, which represents a design choice to handle network propagation issues. The examination also covered the verify_sum function's exclusion of HTR from per-token loops and its reliance on expected HTR delta, noting considerations for future HTR authority features.

Sequence Number Handling Analysis:


The examination of sequence number handling revealed the rationale behind allowing non-sequential transactions. The system distinguishes between two cases: lower or equal sequence numbers (which can be prevented safely) and non-consecutive sequence numbers (which should not be prevented lightly). The MAX_SEQNUM_JUMP_SIZE allows nodes to accept transactions with non-consecutive sequence numbers to handle network propagation issues where retry transactions might fail to propagate to all nodes.


This design choice enables sophisticated wallets to handle high throughput scenarios, though the practical utility remains unclear. The examination covered potential disadvantages of allowing sequence number jumps, particularly regarding global state consistency during network propagation delays.


Contract Creation and Blueprint Analysis:


The examination of contract creation mechanisms revealed the distinction between blueprints and contracts. A contract is an instance of a blueprint, similar to instantiating an object from a class in object-oriented programming. Contract IDs are always derived from the transaction ID of the transaction that created the contract, while blueprint IDs can be either hard-coded manually generated 32-byte IDs for builtin blueprints or transaction IDs for on-chain blueprints (OCBs).

The examination covered how the nc_id field serves different purposes during contract creation versus contract execution. During contract creation, the nc_id contains the blueprint ID, while during contract execution, it contains the contract ID. This dual-purpose usage was examined for potential security implications and validation requirements.

Action Validation Analysis:


The examination of action validation revealed the predefined set of allowed action combinations:

ALLOWED_ACTION_SETS: frozenset[frozenset[NCActionType]] = frozenset([
    frozenset(),
    frozenset([NCActionType.DEPOSIT]),
    frozenset([NCActionType.WITHDRAWAL]),
    frozenset([NCActionType.GRANT_AUTHORITY]),
    frozenset([NCActionType.ACQUIRE_AUTHORITY]),
    frozenset([NCActionType.DEPOSIT, NCActionType.GRANT_AUTHORITY]),
    frozenset([NCActionType.DEPOSIT, NCActionType.ACQUIRE_AUTHORITY]),
    frozenset([NCActionType.WITHDRAWAL, NCActionType.GRANT_AUTHORITY]),
    frozenset([NCActionType.WITHDRAWAL, NCActionType.ACQUIRE_AUTHORITY]),
])

The examination covered why multiple actions for the same token UUID are not allowed and why deposit + withdrawal is not permitted on a single transaction, revealing the underlying business logic that governs transaction validation.


Transaction Signing and Verification Analysis:


The examination of transaction signing mechanisms revealed that nano actions are part of the transaction signature process. The verification process is implemented in hathor/verification/nano_header_verifier.py, where the complete transaction including nano actions is signed and verified. This ensures that nano actions cannot be modified without invalidating the transaction signature.


Authority System Analysis:


The comprehensive examination of the authority system revealed the sophisticated mechanisms for token mint and melt authority management. The authority system operates on an account-based model within the nanocontracts environment, while maintaining compatibility with the UTXO-based Hathor blockchain. Authorities are tracked in UTXOs like regular transfers, allowing authority holders to transfer mint/melt privileges to contracts or other addresses.


The authority acquisition attack testing confirmed that contracts without mint/melt authority cannot acquire these privileges from other contracts through crafted method calls due to proper security controls. The proxy call attack testing confirmed that the proxy call mechanism maintains proper security boundaries and prevents unauthorized operations through existing validation mechanisms. All examined attack scenarios were successfully prevented by the security controls.

Action System Design Analysis:


The examination of the action system design revealed the rationale behind the current implementation. The system provides maximum flexibility for blueprint reusability, allowing a single blueprint to create multiple contracts with different token pairs. This design choice enables scenarios such as a single liquidity pool blueprint being used to create pools with different token pairs by passing the token pair in the initialize method.

The examination covered the trade-offs between protocol-level restrictions and contract-level validation, particularly regarding token-specific whitelisting. While the current approach provides maximum flexibility, it requires developers to implement manual validation logic to prevent unintended token deposits and withdrawals.


hathor/transaction/scripts/execute.py

The script execution engine provides the foundation for processing P2PKH/P2SH scripts within the nanocontracts environment. The detailed review covered the script execution engine that processes various script types, analyzing signature validation logic and cryptographic verification mechanisms. Stack management analysis reviewed stack depth limits and memory management during script execution, while opcode validation examined bounds checking and execution limits to ensure proper script processing.

13.2 Transaction Validation Deep Dive


hathor/verification/nano_header_verifier.py

The nano header verification system provides comprehensive validation for nano contract transactions, ensuring proper signature verification and action validation. The examination covered the complete signature verification process for nano contract transactions, reviewing limits on script size and signature operations. Action validation analysis examined the allowed action sets and validation logic for nano actions, while address format checking verified proper address validation and format verification.


Action Set Analysis:


The action set analysis revealed the predefined set of allowed action combinations and the underlying business logic that governs transaction validation. The examination of token-specific restrictions covered why multiple actions for the same token UUID are not allowed, while deposit/withdrawal logic examination revealed the business logic that prevents simultaneous deposit and withdrawal on the same token. Authority management review covered grant and acquire authority action validation, ensuring proper authorization controls.

13.3 Transaction Storage and State Management


hathor/transaction/storage/

The transaction storage system provides the persistence layer for nano contract transactions and associated state. The examination covered how nano contract transactions are stored and indexed, reviewing mechanisms for persisting contract state across transactions. Transaction metadata analysis examined metadata storage and retrieval for nano contracts, ensuring proper data persistence and retrieval mechanisms.

14. Nano Contracts Core

14.1 Execution Engine Deep Analysis


The nanocontracts execution engine represents the core runtime environment that orchestrates all contract operations and method invocations. The examination focused on the comprehensive execution engine implementation that manages contract lifecycle, method calls, and security boundaries.


hathor/nanocontracts/runner/runner.py (1021 lines)

The main execution engine serves as the central orchestrator for all contract method calls and syscall processing. The comprehensive examination covered the core execution engine that orchestrates contract method calls, reviewing how methods are invoked and syscalls are processed. Recursion depth control analysis examined recursion limits and call stack management, while call tracing and validation mechanisms were examined to understand how execution is monitored and validated.

Resource consumption tracking analysis reviewed fuel and memory consumption tracking mechanisms, ensuring proper resource management during contract execution. Cross-contract communication analysis examined inter-contract call mechanisms and security boundaries, understanding how contracts can safely interact with each other while maintaining proper isolation.


Key Execution Engine Components:


The execution engine implements several critical security components that ensure proper contract execution. Call stack management enforces MAX_RECURSION_DEPTH (100) and MAX_CALL_COUNTER (250) limits to prevent infinite recursion and excessive call depth. Syscall validation provides comprehensive review of all syscall methods and their security restrictions, ensuring that only authorized operations can be performed.

Method parameter validation includes thorough analysis of parameter parsing and type checking, while return value handling reviews return value processing and type safety mechanisms. Exception propagation analysis examines error handling and exception management throughout the execution engine, ensuring proper error handling and recovery mechanisms.


Resource Management and Metering:


Note: Resource management and metering (memory limits, CPU limits, and gas mechanisms) were intentionally excluded from the scope of this audit due to known limitations in the current implementation that would require significant architectural changes.


The resource management analysis examined the current MeteredExecutor implementation structure. The executor framework includes fuel and memory limit parameters but does not enforce them during execution in the current implementation. The exec() call operates without metering constraints, and recursion depth limits in the runner are enforced through call tracking mechanisms rather than execution engine validation.


Current Security Measures: The system currently relies on On-Chain Blueprint (OCB) restrictions and AST-based validation as the primary security mechanisms to prevent resource abuse. The AST validation system effectively prevents dangerous code patterns before execution, while OCB restrictions limit the complexity and size of deployable contracts.


The Python AST compiler warning about stack depth limitations when compiling large/complex strings was examined for potential denial-of-service scenarios. The built-in function filtering in custom_builtins.py was analyzed for completeness and potential bypass scenarios.

Resource Management Implementation Analysis:


Note: This section describes implementation details that were examined but fall outside the audit scope due to known limitations requiring architectural redesign.


The examination of the resource management implementation revealed that on the current audited branch/commit, there was no active enforcement of memory or fuel usage constraints. The runner interface with the MeteredExecutor was examined, noting that the executor framework exists but does not perform resource constraint validation during execution. This implementation represents a known limitation that is addressed through alternative security mechanisms including AST validation and OCB restrictions rather than runtime resource metering.

Denial of Service Analysis:


The examination of denial-of-service possibilities revealed areas of concern in the resource management system. The MeteredExecutor implementation was tested with resource-intensive scripts:

script = '''
for i in range(1000000):
    print(i)
'''

MeteredExecutor(fuel=1, memory_limit=1).exec(script)

This testing confirmed that the current implementation does not enforce fuel and memory limits during execution, which represents a known architectural limitation. Important: The system currently prevents such resource-intensive code through AST-based validation in _RestrictionsVisitor, which analyzes and blocks potentially problematic patterns before execution occurs. The AST validation serves as the primary defense mechanism against resource abuse attacks.

Execution Engine Testing:


The comprehensive testing of the execution engine included various attack scenarios and edge cases. The testing revealed that the execution engine properly handles method invocation and parameter validation, but resource consumption tracking could potentially be bypassed through careful manipulation of the execution environment.

14.2 Blueprint System Analysis


hathor/nanocontracts/blueprint.py

The blueprint system provides the foundation for contract definition and validation within the nanocontracts framework. The comprehensive examination covered the _BlueprintBase metaclass that handles field initialization, reviewing method validation and type annotation processing mechanisms. Field initialization analysis examined how fields are created and initialized from type annotations, while forbidden name validation review covered restrictions on field names and method names to prevent conflicts with system functions.


Blueprint Security Features:


The blueprint security features provide critical protection mechanisms for contract definition. Field name restrictions analysis examined forbidden names like 'syscall' and 'log' that could conflict with system functions, while underscore prefix prevention review covered restrictions on field names starting with underscore to prevent access to private attributes. Type validation analysis examined type checking for field declarations, while default value handling review covered current limitations on field default values and their security implications.

14.3 Storage System Deep Dive


hathor/nanocontracts/storage/contract_storage.py

The storage system provides the persistence layer for all contract state and data. The comprehensive examination covered how contract state is stored and managed, reviewing token balance management and authority tracking mechanisms. Attribute storage analysis examined how contract attributes are stored and retrieved, while state consistency review covered the mechanisms for maintaining state consistency across all contract operations.


Storage Security Analysis:


The storage security analysis revealed the critical mechanisms that ensure data integrity and security. Balance manipulation analysis examined balance addition, subtraction, and authority management operations, ensuring that all balance changes are properly validated and recorded. State isolation review covered how contract states are isolated from each other, preventing unauthorized access and data corruption.

Atomic commits analysis examined the transaction-like commit mechanisms that ensure data consistency, while rollback capability review covered state rollback mechanisms for failed transactions, ensuring that the system can recover from failed operations without data corruption.


Storage Implementation Notes:


The examination of the storage implementation revealed several areas of concern. The get_blueprint_id function must be set via set_blueprint_id when contract is created to ensure correct values. This is done during changes commit call, but the changes_tracker should also call set_blueprint_id to work properly.

The changes tracker uses the same BalanceKey for tracking authorities and balances, which could potentially lead to confusion or conflicts. The reset function in hathor/nanocontracts/storage/changes_tracker.py should also discard _authorities_diff and _created_tokens, as this could be problematic for information reported via _get_mutable_balance or get_all_balances.


Changes Tracker Implementation Analysis:


The examination of the changes tracker implementation revealed the sophisticated mechanisms for handling reentrancy scenarios. The system maintains one change tracker per call to handle cases where Contract A calls Contract B, which then calls Contract A again. This design choice prevents the second call to Contract A from replacing the original changes tracker, ensuring that the original tracker continues to be used when the nested calls finish and execution of the original Contract A call resumes.

The examination covered the implications of this design for future exception control blocks, as the current implementation does not allow try/except blocks in blueprints. The system is designed to support exception control blocks in the future while maintaining proper state isolation between different call contexts.


hathor/nanocontracts/storage/patricia_trie.py

The Patricia trie implementation serves as the core state storage mechanism, providing a Merkle tree-based approach to data persistence. The detailed examination covered the Patricia trie used for state storage, reviewing hash-based node identification mechanisms. Change propagation analysis examined how changes propagate from leaves to root through the trie structure, while trie integrity review covered the mechanisms for maintaining trie consistency across all operations.


Trie Implementation Analysis:


The examination of the Patricia trie implementation revealed the core storage mechanism:

from hathor.nanocontracts.storage.backends import MemoryNodeTrieStore
from hathor.nanocontracts.storage.patricia_trie import Node, PatriciaTrie

store = MemoryNodeTrieStore()
trie = PatriciaTrie(store)

The trie implementation uses SHA1 for node ID calculation, which represents a significant security concern. The examination covered how node changes propagate through the trie structure and the mechanisms for maintaining trie consistency across all operations.


Trie Integrity Notes:


The examination revealed that the trie correctly propagates leaf node changes until the root by updating node IDs. However, the root can always be updated via trie.update(b'', b'Root Content'), which could potentially be exploited. When committing changes to the database, the initial root is not removed, but this shouldn't be a problem as the db stores IDs and when a node is updated or any of its children, the ID does change.

14.4 On-Chain Blueprint Analysis


hathor/nanocontracts/on_chain_blueprint.py

The on-chain blueprint system enables dynamic contract creation and execution within the nanocontracts environment. The comprehensive examination covered dynamic contract creation and execution mechanisms, reviewing code validation and sandboxing processes. Dynamic contract creation analysis examined runtime contract instantiation capabilities, while security boundaries review covered sandboxing mechanisms and execution isolation to ensure proper security controls.

14.5 Context Management Analysis


hathor/nanocontracts/context.py

The context management system provides the execution environment for all contract operations. The comprehensive examination covered the Context class that provides execution environment, reviewing how caller identity is verified and managed. Transaction metadata analysis examined transaction-specific data available to contracts, while action validation review covered how nano actions are validated and processed throughout the execution lifecycle.

Context Security Features:

The context security features provide critical protection mechanisms for contract execution. Immutable properties analysis examined read-only context properties that prevent unauthorized modification, while action validation review covered action list validation using NanoHeaderVerifier to ensure proper action processing. Address format checking analysis examined address validation and format verification, while timestamp handling review covered timestamp validation and usage mechanisms.

Context Immutability Analysis:

The examination of context immutability revealed several security mechanisms:

def func(context: Context) -> int:
    # context.address[0] = 'B'  # TypeError: 'bytes' object does not support item assignment
    # context.actions = []       # property 'actions' of 'Context' object has no setter
    # context.actions[0] = None  # TypeError: 'mappingproxy' object does not support item assignment
    # context.vertex.hash = b'\x00' * 32  # FrozenInstanceError
    # context.vertex.weight = 1234567890   # FrozenInstanceError
    return 42

The context object implements strict immutability controls, preventing modification of critical properties like address, actions, and vertex data. This ensures that contract execution cannot modify the execution context, maintaining security boundaries throughout the execution lifecycle.

14.6 Method System Analysis


hathor/nanocontracts/method.py

The method system provides the framework for contract method definition and execution. The comprehensive examination covered method parsing and validation, reviewing parameter type checking and validation mechanisms. Return value handling analysis examined return type validation and processing, while decorator processing review covered @public, @view, and @fallback decorator handling and their security implications.


Method Security Analysis:


The method security analysis examined the critical aspects of method execution and security. Parameter validation analysis covered input parameter validation and type checking, while return type safety review examined return value type safety and validation mechanisms. Exception handling analysis examined method exception propagation and handling, while caller validation review covered method caller authentication and authorization mechanisms.


Method Parameter Validation:


The examination of method parameter validation revealed potential areas of concern in the parameter parsing system:

class TestClass():
    def test():
        pass

Method.from_callable(TestClass.test)

Output:

Traceback (most recent call last):
  File "hathor-core/test_blue.py", line xx, in <module>
    Method.from_callable(TestClass.test)  # This should raise an error because the method is not callable
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "hathor-core/hathor/nanocontracts/method.py", line 216, in from_callable
    self_param = next(iter_params)
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
StopIteration

This test case demonstrated that the Method.from_callable function could fail with a StopIteration exception when attempting to parse parameters from methods that don't have the expected self and context parameters. While this is prevented by the @public decorator validation, it represents a potential edge case in the parameter parsing system.


Method Visibility Notes:


The examination of method visibility revealed that for the fallback method, the code verifies that both fallback and @fallback annotation are present. If both are NOT present, the code reverts. You cannot define a function named fallback without the annotation, which provides an additional layer of validation.

14.7 Custom Builtins Analysis


hathor/nanocontracts/custom_builtins.py

The custom builtins system provides the restricted execution environment for nanocontracts. The comprehensive examination covered the restricted built-in function set, reviewing which Python built-ins are available to contracts and their security implications. Security sandboxing analysis examined sandboxing mechanisms and restrictions, while disabled function handling review covered how dangerous functions are disabled to prevent security breaches.


Sandbox Security Analysis:


The sandbox security analysis examined the sophisticated mechanisms used to prevent unauthorized access and execution. Built-in function filtering analysis examined which functions are allowed versus disabled, while reflection prevention review covered mechanisms to prevent reflection-based attacks. System call prevention analysis examined how system calls are prevented, while import restrictions review covered import limitations and module access controls.


Note: The testing methodology included examination of theoretical attack vectors such as reflection-based escapes through __class__, __subclasses__(), and __globals__ access patterns. However, these attack vectors are effectively prevented by the AST-based validation system that blocks any code containing double underscore (__) patterns before execution. The AST validation serves as the primary security mechanism that renders these theoretical attacks non-viable in practice.

Advanced Sandbox Security Analysis:


The comprehensive sandbox security analysis examined theoretical attack vectors within the Python execution environment to assess the robustness of the security mechanisms. The analysis included examination of reflection-based escape patterns that could theoretically access dangerous functions through class traversal mechanisms using __class__, __subclasses__(), and __globals__ access patterns.


The theoretical attack analysis examined multiple vectors such as accessing os.system() through tuple subclasses, object subclasses, and exception subclasses. The examination also reviewed the SafeObject wrapper implementation and potential theoretical limitations regarding string coercion and unwrapped object returns.


Critical Security Note: All examined attack vectors are effectively prevented by the AST-based validation system in _RestrictionsVisitor. The AST validator blocks any code containing double underscore (__) patterns before execution, making these theoretical attacks impossible to execute in practice. The AST validation serves as the primary security boundary that prevents malicious code from reaching the execution environment.

Theoretical Sandbox Bypass Techniques:


The examination analyzed theoretical sandbox bypass techniques to validate the security mechanisms:

# Via tuple subclasses
subclasses = ().__class__.__base__.__subclasses__()
for cls in subclasses:
    if cls.__name__ == 'Popen':
        os = cls.__init__.__globals__['os']
        os.system('uname -a')
        break

# Via object subclasses
for cls in object.__subclasses__():
    if cls.__name__ == 'Popen':
        os = cls.__init__.__globals__['os']
        os.system('uname -a')
        break

# Via exception subclasses
for cls in Exception.__subclasses__():
    try:
        g = cls.__init__.__globals__
        if 'os' in g:
            g['os'].system('uname -a')
            break
    except:
        continue

Security Validation: These theoretical techniques demonstrate attack patterns that would be blocked by the AST-based validation system before execution. Any code containing double underscore (__) patterns is rejected during the AST validation phase, preventing these attacks from reaching the execution environment. The AST validation serves as an effective first-line defense against reflection-based attacks.

Built-in Function Analysis:


The examination of the built-in function environment revealed that the 'oct': case in custom_builtins.py should be builtins.oct not builtins.object. The examination covered all available built-in functions and their security implications, including the disabled functions that return _generate_disabled_builtin_func wrappers.


Custom Builtins Implementation Analysis:


The examination of the custom builtins implementation revealed a typo in the custom_builtins.py file where the 'oct': case was incorrectly mapped to builtins.object instead of builtins.oct. This typo was identified during the audit and represents a potential issue in the built-in function filtering system. The examination covered the implications of this typo for the restricted execution environment and the potential for bypassing intended restrictions.

15. Verification & Validation

15.1 AST-Based Code Validation


The verification and validation system provides the security foundation for nanocontracts through comprehensive code analysis and validation mechanisms. Our analysis focused on the AST-based code validation system that ensures only safe and authorized code can be executed within the nanocontracts environment.


hathor/verification/on_chain_blueprint_verifier.py

The on-chain blueprint validation system implements comprehensive AST-based code validation to ensure security and prevent malicious code execution. Our analysis examined the complete AST analysis and restrictions framework, reviewing the Abstract Syntax Tree analysis for security vulnerabilities. Import whitelisting analysis examined allowed import statements and module access controls, while code sandboxing review covered the execution sandboxing mechanisms that isolate contract execution.


AST Security Analysis:


The AST security analysis revealed the sophisticated mechanisms used to detect and prevent dangerous code patterns. Dunder method detection analysis examined how __class__, __subclasses__, and other reflection methods are detected and blocked to prevent reflection-based attacks. Import validation review covered import statement validation and restrictions, while function call analysis examined function call validation and restrictions to prevent unauthorized operations.

Variable access control analysis reviewed variable access patterns and restrictions, ensuring that contracts cannot access unauthorized data or perform dangerous operations through variable manipulation.

15.2 Transaction Verification


hathor/verification/verification_service.py

The transaction verification service provides the orchestration layer for all verification activities within the nanocontracts system. Our comprehensive analysis examined the verification service that coordinates multi-stage validation processes, reviewing the complete multi-stage validation workflow that ensures proper transaction processing. Error handling and reporting analysis examined the mechanisms for error handling and reporting throughout the verification process, while Python script validation review covered the verify_python_script functionality that validates contract code before execution.


Verification Security Analysis:


The verification security analysis revealed the sophisticated mechanisms used to ensure transaction integrity. Script validation analysis examined Python script syntax and semantic validation processes, while restriction enforcement review covered how code restrictions are enforced throughout the verification pipeline. Error propagation analysis examined error handling and propagation mechanisms, ensuring that verification failures are properly handled and reported.


Validation completeness review examined the coverage and completeness of the verification system, ensuring that all critical aspects of transaction processing are properly validated before execution.

15.3 Nano Header Verification


hathor/verification/nano_header_verifier.py

The nano header verification system provides comprehensive validation for nano contract transactions, ensuring proper signature verification and action validation. The examination covered the complete signature verification process for nano contract transactions, reviewing limits on script size and signature operations. Action validation analysis examined the allowed action sets and validation logic for nano actions, while address format checking verified proper address validation and format verification.


Verification Security Analysis:


The verification security analysis examined the cryptographic foundations of the nano contracts system. Signature validation analysis covered the cryptographic signature verification processes, while action set validation review examined allowed action combinations and restrictions. Script execution limits analysis examined resource limits for script execution, while address validation review covered address format and checksum validation mechanisms.

16. Storage & Indexes

16.1 Contract Storage Analysis


The storage and indexing system provides the persistence layer for nanocontracts state and ensures proper data management across the entire system. Our analysis focused on the comprehensive storage mechanisms that maintain contract state, balance tracking, and data integrity.


hathor/nanocontracts/storage/contract_storage.py

The contract storage system implements comprehensive state management for all nanocontracts, providing the foundation for persistent contract state. Our analysis examined the complete contract state storage and management mechanisms, reviewing token balance management and authority tracking systems. Attribute storage analysis examined how contract attributes are stored and retrieved, while state consistency review covered the mechanisms for maintaining state consistency across the entire system.


Storage Security Analysis:


The storage security analysis revealed the critical mechanisms that ensure data integrity and security. Balance manipulation analysis examined balance addition, subtraction, and authority management operations, ensuring that all balance changes are properly validated and recorded. State isolation review covered how contract states are isolated from each other, preventing unauthorized access and data corruption.

Atomic commits analysis examined the transaction-like commit mechanisms that ensure data consistency, while rollback capability review covered state rollback mechanisms for failed transactions, ensuring that the system can recover from failed operations without data corruption.

16.2 Patricia Trie Implementation


hathor/nanocontracts/storage/patricia_trie.py

The Patricia trie implementation serves as the core state storage mechanism, providing a Merkle tree-based approach to data persistence. Our detailed analysis examined the Patricia trie used for state storage, reviewing the hash-based node identification using SHA1 for node ID calculation. Change propagation analysis examined how changes propagate from leaves to root through the trie structure, while trie integrity review covered the mechanisms for maintaining trie consistency across all operations.


Trie Security Analysis:


The trie security analysis revealed critical aspects of the state storage system. Hash function security analysis examined the use of SHA1 for node ID calculation and its security implications, while change propagation review covered how node changes propagate through the trie structure. Root integrity analysis examined root hash calculation and verification mechanisms, while storage efficiency review covered storage optimization and memory usage patterns.

16.3 Block Storage Analysis


hathor/nanocontracts/storage/block_storage.py

The block storage system provides the persistence layer for nano contract data at the block level, ensuring proper state management across the blockchain. Our analysis examined how nano contract data is stored at the block level, reviewing address sequence number tracking and validation mechanisms. State persistence analysis examined how contract state persists across blocks, while reorg handling review covered how state changes are handled during blockchain reorganizations.


Block Storage Notes:


Our analysis of block storage revealed that the address does allow setting a higher seqnum, but there is no check verifying that assert seqnum == old_seqnum + 1. Instead, it uses assert seqnum > old_seqnum, which could potentially allow non-sequential transaction ordering.

16.4 Changes Tracker Analysis


hathor/nanocontracts/storage/changes_tracker.py

The changes tracker system provides comprehensive tracking of contract state changes throughout the execution lifecycle. Our analysis examined how contract state changes are tracked, reviewing balance change tracking and diff management mechanisms. Authority tracking analysis examined authority change tracking and management, while token creation tracking review covered new token creation and tracking processes.


Changes Tracker Security Analysis:


The changes tracker security analysis examined the mechanisms that ensure data integrity during state changes. Diff management analysis covered how state changes are tracked and managed, while balance consistency review examined balance consistency checking and validation mechanisms. Authority management analysis covered authority grant and revocation tracking, while reset functionality review examined change tracker reset mechanisms and cleanup processes.

16.5 Index Management


hathor/indexes/manager.py

The index management system provides efficient querying and tracking capabilities for nano contract activities. Our analysis examined how nano contract history is indexed and tracked, reviewing contract creation event tracking mechanisms. Blueprint history management analysis examined blueprint version tracking and history, while token balance indexing review covered token balance indexing and querying capabilities.


Index Security Analysis:


The index security analysis examined the data integrity and consistency mechanisms within the indexing system. Data consistency analysis examined index consistency with underlying state, while race condition handling review covered concurrent access and race condition management. Query performance analysis examined index query performance and optimization, while data integrity review covered index data integrity and validation mechanisms.

17. Consensus Integration

17.1 Consensus Algorithm Integration

The consensus integration system ensures that nanocontracts properly integrate with the Hathor blockchain consensus mechanism, maintaining state consistency and proper transaction processing across the network.


hathor/consensus/consensus.py

The consensus algorithm integration provides the foundation for nano contract execution within the blockchain consensus framework. Our comprehensive analysis examined how nano contracts integrate with consensus, reviewing how voided transactions affect contract state and the mechanisms for handling transaction invalidation. State consistency checks analysis examined state consistency validation during consensus, while reorg handling for NCs review covered how blockchain reorganizations affect contract state and the recovery mechanisms.


Consensus Security Analysis:


The consensus security analysis examined the critical aspects of contract execution within the consensus framework. Transaction ordering analysis examined how transaction ordering affects contract execution and the mechanisms for ensuring proper execution order. State consistency review covered state consistency across network nodes, while conflict resolution analysis examined conflict resolution mechanisms for contract state during network partitions.

Fork safety review covered fork safety mechanisms for contract state, ensuring that contract state remains consistent even during blockchain forks and reorganizations.


Consensus Integration Analysis:


Our analysis of consensus integration revealed that transactions are only executed when a block confirms them, at least if they involve contract calls. The block sorts and executes transactions, ensuring that when nodes sync, they execute transactions using the same order as determined by the block, rather than by the order where they received the transactions. This design choice prevents consensus discrepancies that could arise from network propagation delays.


The analysis examined how this consensus mechanism affects transaction ordering and state consistency, particularly in scenarios where transactions might be received in different orders by different nodes. The system ensures that all nodes execute transactions in the same order when processing blocks, maintaining consistency across the network.

17.2 Consensus Settings


hathor/consensus/consensus_settings.py

The consensus settings system provides the configuration framework for nano contract consensus parameters. Our analysis examined consensus parameters specific to nano contracts, reviewing execution limits and resource constraints that ensure proper resource management. Validation rules analysis examined validation rules and enforcement mechanisms, while security parameters review covered security-related consensus parameters that protect the system from various attack vectors.

18. Access Control & Permissions

18.1 Syscall Restrictions


The access control and permissions system provides the security foundation for nanocontracts by implementing comprehensive restrictions and validation mechanisms. Our analysis focused on the syscall restrictions and method visibility controls that ensure proper security boundaries.


hathor/nanocontracts/runner/runner.py

The syscall restriction system provides comprehensive validation of syscall method validation and restrictions, ensuring that only authorized operations can be performed. Our analysis examined restrictions on syscalls from view methods, while authority management analysis covered authority grant and revocation syscalls. Resource management review covered resource allocation and management syscalls to ensure proper resource control.


Syscall Security Analysis:


The syscall security analysis examined the critical aspects of method execution and access control. Method visibility analysis covered public versus view method restrictions, while cross-contract calls review examined inter-contract communication security mechanisms. Authority control analysis examined authority management and validation, while resource limits review covered resource consumption limits and enforcement mechanisms.

18.2 Method Visibility and Access Control


hathor/nanocontracts/types.py

The method visibility system provides the framework for controlling access to contract methods. Our analysis examined @public, @view, and @fallback decorators and their security implications, reviewing method access control mechanisms. Visibility rules analysis examined method visibility rules and restrictions, while authorization logic review covered authorization and permission checking mechanisms.

18.3 Context Isolation


hathor/nanocontracts/context.py

The context isolation system ensures proper separation between different contract execution environments. Our analysis examined how execution contexts are isolated, reviewing caller identity verification and validation mechanisms. Metadata protection analysis examined transaction metadata protection and access control, while action validation review covered action validation and authorization mechanisms.


Inter-Contract Attack Scenarios:


Our security analysis examined theoretical attack scenarios to validate the robustness of inter-contract communication mechanisms. The testing methodology included authority acquisition attack scenarios where contracts without mint/melt authority would theoretically attempt to acquire these privileges from other contracts, proxy call attack scenarios that could theoretically bypass security boundaries, and RNG manipulation scenarios where contracts could theoretically override random number generation functions to influence other contracts' behavior. Security Validation: All tested attack scenarios were successfully prevented by the existing security mechanisms.


Inter-Contract Attack Analysis:


Our comprehensive analysis of inter-contract attack scenarios examined the robustness of the contract communication system against various theoretical attack vectors. The test scenarios included sophisticated attack patterns such as authority escalation attempts, proxy call exploitation attempts, and state manipulation through crafted actions.

The authority acquisition attack testing demonstrated that contracts without mint/melt authority cannot acquire these privileges from other contracts through crafted method calls due to proper access controls. The proxy call attack testing confirmed that the proxy call mechanism maintains proper security boundaries and prevents unauthorized operations. Security Validation: All examined attack scenarios were successfully prevented by the existing security mechanisms, confirming the robustness of the inter-contract communication system.


The RNG manipulation attempts showed how contracts could potentially override random number generation functions to influence other contracts' behavior, creating opportunities for predictable outcomes in supposedly random processes.


Contract Communication Testing:


Our comprehensive testing of inter-contract communication included various theoretical attack scenarios and edge cases to validate system security. The testing confirmed that the contract communication system properly handles method invocation and parameter validation. Note: Resource consumption tracking limitations were identified as out-of-scope items that rely on alternative security mechanisms (AST validation and OCB restrictions).


The testing confirmed that the contract communication system properly enforces security boundaries and prevents unauthorized access. The error handling mechanisms were found to be functional, with potential areas for improvement identified for enhanced debugging and recovery capabilities.

RNG Implementation Notes:


Our analysis of the RNG implementation revealed that it is not a true random number generator, but pseudo-random with seed. The implementation uses ChaCha20 for encryption, and the same seed produces the same output:

encryptor = Cipher(algorithms.ChaCha20(h, h[:16]), mode=None).encryptor()
encryptor.update(b'\0' * 10)  # Always produces the same output

This deterministic behavior could potentially be exploited by attackers who can predict or manipulate the return values.

19. RISK METHODOLOGY

Every vulnerability and issue observed by Halborn is ranked based on two sets of Metrics and a Severity Coefficient. This system is inspired by the industry standard Common Vulnerability Scoring System.
The two Metric sets are: Exploitability and Impact. Exploitability captures the ease and technical means by which vulnerabilities can be exploited and Impact describes the consequences of a successful exploit.
The Severity Coefficients is designed to further refine the accuracy of the ranking with two factors: Reversibility and Scope. These capture the impact of the vulnerability on the environment as well as the number of users and smart contracts affected.
The final score is a value between 0-10 rounded up to 1 decimal place and 10 corresponding to the highest security risk. This provides an objective and accurate rating of the severity of security vulnerabilities in smart contracts.
The system is designed to assist in identifying and prioritizing vulnerabilities based on their level of risk to address the most critical issues in a timely manner.

19.1 EXPLOITABILITY

Attack Origin (AO):
Captures whether the attack requires compromising a specific account.
Attack Cost (AC):
Captures the cost of exploiting the vulnerability incurred by the attacker relative to sending a single transaction on the relevant blockchain. Includes but is not limited to financial and computational cost.
Attack Complexity (AX):
Describes the conditions beyond the attacker’s control that must exist in order to exploit the vulnerability. Includes but is not limited to macro situation, available third-party liquidity and regulatory challenges.
Metrics:
EXPLOITABILITY METRIC (mem_eme​)METRIC VALUENUMERICAL VALUE
Attack Origin (AO)Arbitrary (AO:A)
Specific (AO:S)
1
0.2
Attack Cost (AC)Low (AC:L)
Medium (AC:M)
High (AC:H)
1
0.67
0.33
Attack Complexity (AX)Low (AX:L)
Medium (AX:M)
High (AX:H)
1
0.67
0.33
Exploitability EEE is calculated using the following formula:

E=∏meE = \prod m_eE=∏me​

19.2 IMPACT

Confidentiality (C):
Measures the impact to the confidentiality of the information resources managed by the contract due to a successfully exploited vulnerability. Confidentiality refers to limiting access to authorized users only.
Integrity (I):
Measures the impact to integrity of a successfully exploited vulnerability. Integrity refers to the trustworthiness and veracity of data stored and/or processed on-chain. Integrity impact directly affecting Deposit or Yield records is excluded.
Availability (A):
Measures the impact to the availability of the impacted component resulting from a successfully exploited vulnerability. This metric refers to smart contract features and functionality, not state. Availability impact directly affecting Deposit or Yield is excluded.
Deposit (D):
Measures the impact to the deposits made to the contract by either users or owners.
Yield (Y):
Measures the impact to the yield generated by the contract for either users or owners.
Metrics:
IMPACT METRIC (mIm_ImI​)METRIC VALUENUMERICAL VALUE
Confidentiality (C)None (C:N)
Low (C:L)
Medium (C:M)
High (C:H)
Critical (C:C)
0
0.25
0.5
0.75
1
Integrity (I)None (I:N)
Low (I:L)
Medium (I:M)
High (I:H)
Critical (I:C)
0
0.25
0.5
0.75
1
Availability (A)None (A:N)
Low (A:L)
Medium (A:M)
High (A:H)
Critical (A:C)
0
0.25
0.5
0.75
1
Deposit (D)None (D:N)
Low (D:L)
Medium (D:M)
High (D:H)
Critical (D:C)
0
0.25
0.5
0.75
1
Yield (Y)None (Y:N)
Low (Y:L)
Medium (Y:M)
High (Y:H)
Critical (Y:C)
0
0.25
0.5
0.75
1
Impact III is calculated using the following formula:

I=max(mI)+∑mI−max(mI)4I = max(m_I) + \frac{\sum{m_I} - max(m_I)}{4}I=max(mI​)+4∑mI​−max(mI​)​

19.3 SEVERITY COEFFICIENT

Reversibility (R):
Describes the share of the exploited vulnerability effects that can be reversed. For upgradeable contracts, assume the contract private key is available.
Scope (S):
Captures whether a vulnerability in one vulnerable contract impacts resources in other contracts.
Metrics:
SEVERITY COEFFICIENT (CCC)COEFFICIENT VALUENUMERICAL VALUE
Reversibility (rrr)None (R:N)
Partial (R:P)
Full (R:F)
1
0.5
0.25
Scope (sss)Changed (S:C)
Unchanged (S:U)
1.25
1
Severity Coefficient CCC is obtained by the following product:

C=rsC = rsC=rs

The Vulnerability Severity Score SSS is obtained by:

S=min(10,EIC∗10)S = min(10, EIC * 10)S=min(10,EIC∗10)

The score is rounded up to 1 decimal places.
SeverityScore Value Range
Critical9 - 10
High7 - 8.9
Medium4.5 - 6.9
Low2 - 4.4
Informational0 - 1.9

20. SCOPE

REPOSITORY
(a) Repository: hathor-core
(b) Assessed Commit ID: 7318c45
(c) Items in scope:
  • hathor/nanocontracts/__init__.py
  • hathor/nanocontracts/api_arguments_parser.py
  • hathor/nanocontracts/balance_rules.py
  • hathor/nanocontracts/blueprint.py
  • hathor/nanocontracts/blueprint_env.py
  • hathor/nanocontracts/blueprint_syntax_validation.py
  • hathor/nanocontracts/blueprints/
  • hathor/nanocontracts/blueprints/__init__.py
  • hathor/nanocontracts/catalog.py
  • hathor/nanocontracts/context.py
  • hathor/nanocontracts/custom_builtins.py
  • hathor/nanocontracts/exception.py
  • hathor/nanocontracts/fields/
  • hathor/nanocontracts/fields/__init__.py
  • hathor/nanocontracts/fields/container_field.py
  • hathor/nanocontracts/fields/deque_field.py
  • hathor/nanocontracts/fields/dict_field.py
  • hathor/nanocontracts/fields/field.py
  • hathor/nanocontracts/fields/nc_type_field.py
  • hathor/nanocontracts/fields/set_field.py
  • hathor/nanocontracts/fields/utils.py
  • hathor/nanocontracts/metered_exec.py
  • hathor/nanocontracts/method.py
  • hathor/nanocontracts/nc_exec_logs.py
  • hathor/nanocontracts/nc_types/
  • hathor/nanocontracts/nc_types/__init__.py
  • hathor/nanocontracts/nc_types/address_nc_type.py
  • hathor/nanocontracts/nc_types/bool_nc_type.py
  • hathor/nanocontracts/nc_types/bytes_nc_type.py
  • hathor/nanocontracts/nc_types/collection_nc_type.py
  • hathor/nanocontracts/nc_types/dataclass_nc_type.py
  • hathor/nanocontracts/nc_types/fixed_size_bytes_nc_type.py
  • hathor/nanocontracts/nc_types/map_nc_type.py
  • hathor/nanocontracts/nc_types/namedtuple_nc_type.py
  • hathor/nanocontracts/nc_types/nc_type.py
  • hathor/nanocontracts/nc_types/null_nc_type.py
  • hathor/nanocontracts/nc_types/optional_nc_type.py
  • hathor/nanocontracts/nc_types/signed_data_nc_type.py
  • hathor/nanocontracts/nc_types/sized_int_nc_type.py
  • hathor/nanocontracts/nc_types/str_nc_type.py
  • hathor/nanocontracts/nc_types/token_uid_nc_type.py
  • hathor/nanocontracts/nc_types/tuple_nc_type.py
  • hathor/nanocontracts/nc_types/utils.py
  • hathor/nanocontracts/nc_types/varint_nc_type.py
  • hathor/nanocontracts/on_chain_blueprint.py
  • hathor/nanocontracts/resources/
  • hathor/nanocontracts/resources/__init__.py
  • hathor/nanocontracts/resources/blueprint.py
  • hathor/nanocontracts/resources/blueprint_source_code.py
  • hathor/nanocontracts/resources/builtin.py
  • hathor/nanocontracts/resources/history.py
  • hathor/nanocontracts/resources/nc_creation.py
  • hathor/nanocontracts/resources/nc_exec_logs.py
  • hathor/nanocontracts/resources/on_chain.py
  • hathor/nanocontracts/resources/state.py
  • hathor/nanocontracts/rng.py
  • hathor/nanocontracts/runner/
  • hathor/nanocontracts/runner/__init__.py
  • hathor/nanocontracts/runner/runner.py
  • hathor/nanocontracts/runner/types.py
  • hathor/nanocontracts/sorter/
  • hathor/nanocontracts/sorter/__init__.py
  • hathor/nanocontracts/sorter/random_sorter.py
  • hathor/nanocontracts/sorter/timestamp_sorter.py
  • hathor/nanocontracts/sorter/types.py
  • hathor/nanocontracts/storage/
  • hathor/nanocontracts/storage/__init__.py
  • hathor/nanocontracts/storage/backends.py
  • hathor/nanocontracts/storage/block_storage.py
  • hathor/nanocontracts/storage/changes_tracker.py
  • hathor/nanocontracts/storage/contract_storage.py
  • hathor/nanocontracts/storage/factory.py
  • hathor/nanocontracts/storage/maybedeleted_nc_type.py
  • hathor/nanocontracts/storage/node_nc_type.py
  • hathor/nanocontracts/storage/patricia_trie.py
  • hathor/nanocontracts/storage/token_proxy.py
  • hathor/nanocontracts/storage/types.py
  • hathor/nanocontracts/types.py
  • hathor/nanocontracts/utils.py
  • hathor/nanocontracts/vertex_data.py
  • Initial review: https://github.com/HathorNetwork/hathor-core/commit/07ea5a7b8fe4f934b1ceb4bc086507f01e1dc6bb
  • hathor/nanocontracts/__init__.py
  • hathor/nanocontracts/api_arguments_parser.py
  • hathor/nanocontracts/balance_rules.py
↓ Expand ↓
Remediation Commit ID:
  • https://github.com/HathorNetwork/hathor-core/pull/1363
  • 23de8bf
  • https://github.com/HathorNetwork/hathor-core/pull/1378
  • https://github.com/HathorNetwork/hathor-core/pull/1471
  • https://github.com/HathorNetwork/hathor-core/pull/1376
  • c2e6138
  • https://github.com/HathorNetwork/hathor-core/pull/1333
  • https://github.com/HathorNetwork/hathor-core/pull/1375
  • do-not-
Out-of-Scope: New features/implementations after the remediation commit IDs.

21. Assessment Summary & Findings Overview

Critical

0

High

0

Medium

4

Low

1

Informational

16

Security analysisRisk levelRemediation Date
Deterministic random number generationMediumRisk Accepted - 08/20/2025
Invalid custom builtins mappingMediumSolved - 08/20/2025
Incorrect bounds calculation in sized integersMediumSolved - 07/09/2025
Weak hash function in trie node calculationMediumSolved - 08/22/2025
Double proxy call bypasses blueprint validationLowSolved - 10/21/2025
Incomplete method parameter validationInformationalSolved - 08/21/2025
Missing timestamp type validationInformationalSolved - 07/09/2025
Incomplete deserialization validationInformationalNot Applicable - 08/21/2025
Missing cache management in single value fieldsInformationalNot Applicable - 08/22/2025
Missing context immutability enforcementInformationalSolved - 07/22/2025
Missing AST compiler stack depth protectionInformationalAcknowledged - 08/21/2025
Missing resource metering in execution engineInformationalAcknowledged - 08/21/2025
Inadequate input validation in script executionInformationalAcknowledged - 08/21/2025
Inefficient type checking with typoInformationalSolved - 08/21/2025
Incomplete changes tracker resetInformationalSolved - 08/20/2025
Non-sequential transaction allowanceInformationalAcknowledged - 08/21/2025
Union type handling issuesInformationalNot Applicable - 08/21/2025
Missing collection type supportInformationalNot Applicable - 08/20/2025
Missing blueprint syntax validation integrationInformationalAcknowledged - 08/20/2025
Missing action amount validationInformationalAcknowledged - 08/21/2025
Missing token whitelist validationInformationalAcknowledged - 08/20/2025

22. Findings & Tech Details

22.1 Deterministic random number generation

//

Medium

Description
BVSS
AO:A/AC:L/AX:L/R:N/S:U/C:M/A:N/I:M/D:N/Y:N (6.3)
Recommendation
Remediation Comment

22.2 Invalid custom builtins mapping

//

Medium

Description
BVSS
AO:A/AC:L/AX:L/R:N/S:U/C:N/A:L/I:M/D:N/Y:N (5.6)
Recommendation
Remediation Comment
Remediation Hash
https://github.com/HathorNetwork/hathor-core/pull/1363

22.3 Incorrect bounds calculation in sized integers

//

Medium

Description
BVSS
AO:A/AC:L/AX:L/R:N/S:U/C:N/A:N/I:M/D:N/Y:N (5.0)
Recommendation
Remediation Comment
Remediation Hash
https://github.com/HathorNetwork/hathor-core/commit/23de8bf8626c3a99ea59d07af960b01e4441e433

22.4 Weak hash function in trie node calculation

//

Medium

Description
BVSS
AO:A/AC:L/AX:L/R:N/S:U/C:N/A:N/I:M/D:N/Y:N (5.0)
Recommendation
Remediation Comment
Remediation Hash
https://github.com/HathorNetwork/hathor-core/pull/1378

22.5 Double proxy call bypasses blueprint validation

//

Low

Description
Proof of Concept
BVSS
AO:A/AC:L/AX:L/R:N/S:U/C:N/A:N/I:L/D:N/Y:N (2.5)
Recommendation
Remediation Hash
https://github.com/HathorNetwork/hathor-core/pull/1471

22.6 Incomplete method parameter validation

//

Informational

Description
BVSS
AO:S/AC:L/AX:L/C:N/I:H/A:N/D:N/S:U (1.5)
Recommendation
Remediation Comment
Remediation Hash
https://github.com/HathorNetwork/hathor-core/pull/1376

22.7 Missing timestamp type validation

//

Informational

Description
BVSS
AO:S/AC:L/AX:L/C:N/I:H/A:N/D:N/S:U (1.5)
Recommendation
Remediation Comment
Remediation Hash
https://github.com/HathorNetwork/hathor-core/commit/c2e61388d78d3fa181eefdedded00fae40c76d3c

22.8 Incomplete deserialization validation

//

Informational

Description
BVSS
AO:S/AC:L/AX:L/C:N/I:H/A:N/D:N/S:U (1.5)
Recommendation
Remediation Comment

22.9 Missing cache management in single value fields

//

Informational

Description
BVSS
AO:S/AC:L/AX:L/C:N/I:H/A:N/D:N/S:U (1.5)
Recommendation
Remediation Comment

22.10 Missing context immutability enforcement

//

Informational

Description
BVSS
AO:S/AC:L/AX:L/C:N/I:H/A:N/D:N/S:U (1.5)
Recommendation
Remediation Comment
Remediation Hash
https://github.com/HathorNetwork/hathor-core/pull/1333

22.11 Missing AST compiler stack depth protection

//

Informational

Description
BVSS
AO:S/AC:L/AX:L/R:N/S:U/C:N/A:H/I:N/D:N/Y:N (1.5)
Recommendation
Remediation Comment

22.12 Missing resource metering in execution engine

//

Informational

Description
BVSS
AO:A/AC:L/AX:L/R:N/S:U/C:N/A:N/I:N/D:N/Y:N (0.0)
Recommendation
Remediation Comment

22.13 Inadequate input validation in script execution

//

Informational

Description
BVSS
AO:A/AC:L/AX:L/R:N/S:U/C:N/A:N/I:N/D:N/Y:N (0.0)
Recommendation
Remediation Comment

22.14 Inefficient type checking with typo

//

Informational

Description
BVSS
AO:A/AC:L/AX:L/R:N/S:U/C:N/A:N/I:N/D:N/Y:N (0.0)
Recommendation
Remediation Comment
Remediation Hash
https://github.com/HathorNetwork/hathor-core/pull/1375

22.15 Incomplete changes tracker reset

//

Informational

Description
BVSS
AO:A/AC:L/AX:L/R:N/S:U/C:N/A:N/I:N/D:N/Y:N (0.0)
Recommendation
Remediation Comment
Remediation Hash

22.16 Non-sequential transaction allowance

//

Informational

Description
BVSS
AO:A/AC:L/AX:L/R:N/S:U/C:N/A:N/I:N/D:N/Y:N (0.0)
Recommendation
Remediation Comment

22.17 Union type handling issues

//

Informational

Description
BVSS
AO:A/AC:L/AX:L/R:N/S:U/C:N/A:N/I:N/D:N/Y:N (0.0)
Recommendation
Remediation Comment

22.18 Missing collection type support

//

Informational

Description
BVSS
AO:A/AC:L/AX:L/R:N/S:U/C:N/A:N/I:N/D:N/Y:N (0.0)
Recommendation
Remediation Comment

22.19 Missing blueprint syntax validation integration

//

Informational

Description
BVSS
AO:A/AC:L/AX:L/R:N/S:U/C:N/A:N/I:N/D:N/Y:N (0.0)
Recommendation
Remediation Comment

22.20 Missing action amount validation

//

Informational

Description
BVSS
AO:A/AC:L/AX:L/R:N/S:U/C:N/A:N/I:N/D:N/Y:N (0.0)
Recommendation
Remediation Comment

22.21 Missing token whitelist validation

//

Informational

Description
BVSS
AO:A/AC:L/AX:L/R:N/S:U/C:N/A:N/I:N/D:N/Y:N (0.0)
Recommendation
Remediation Comment

Halborn strongly recommends conducting a follow-up assessment of the project either within six months or immediately following any material changes to the codebase, whichever comes first. This approach is crucial for maintaining the project’s integrity and addressing potential vulnerabilities introduced by code modifications.

Table of Contents

  • 1. Introduction
  • 2. Assessment summary
  • 3. Protocol overview
  • 4. Scope of audit
  • 5. Advanced security analysis
    • 5.1 Python sandbox security analysis
    • 5.2 Custom test development
  • 6. Tool-assisted analysis
    • 6.1 Automated static analysis
  • 7. Assessment methodology
    • 7.1 Manual code review process
    • 7.2 Tool-assisted analysis
  • 8. Test coverage and methodology
  • 9. Critical security context
  • 10. Executive summary
  • 11. Detailed assessment coverage
  • 12. Serialization
    • 12.1 Core serialization components
    • 12.2 Serialization security analysis
    • 12.3 Serialization security analysis
  • 13. Transaction processing
    • 13.1 Transaction header analysis
    • 13.2 Transaction validation deep dive
    • 13.3 Transaction storage and state management
  • 14. Nano contracts core
    • 14.1 Execution engine deep analysis
    • 14.2 Blueprint system analysis
    • 14.3 Storage system deep dive
    • 14.4 On-chain blueprint analysis
    • 14.5 Context management analysis
    • 14.6 Method system analysis
    • 14.7 Custom builtins analysis
  • 15. Verification & validation
    • 15.1 Ast-based code validation
    • 15.2 Transaction verification
    • 15.3 Nano header verification
  • 16. Storage & indexes
    • 16.1 Contract storage analysis
    • 16.2 Patricia trie implementation
    • 16.3 Block storage analysis
    • 16.4 Changes tracker analysis
    • 16.5 Index management
  • 17. Consensus integration
    • 17.1 Consensus algorithm integration
    • 17.2 Consensus settings
  • 18. Access control & permissions
    • 18.1 Syscall restrictions
    • 18.2 Method visibility and access control
    • 18.3 Context isolation
  • 19. Risk methodology
  • 20. Scope
  • 21. Assessment summary & findings overview
  • 22. Findings & Tech Details
    1. 22.1 Deterministic random number generation
    2. 22.2 Invalid custom builtins mapping
    3. 22.3 Incorrect bounds calculation in sized integers
    4. 22.4 Weak hash function in trie node calculation
    5. 22.5 Double proxy call bypasses blueprint validation
    6. 22.6 Incomplete method parameter validation
    7. 22.7 Missing timestamp type validation
    8. 22.8 Incomplete deserialization validation
    9. 22.9 Missing cache management in single value fields
    10. 22.10 Missing context immutability enforcement
    11. 22.11 Missing ast compiler stack depth protection
    12. 22.12 Missing resource metering in execution engine
    13. 22.13 Inadequate input validation in script execution
    14. 22.14 Inefficient type checking with typo
    15. 22.15 Incomplete changes tracker reset
    16. 22.16 Non-sequential transaction allowance
    17. 22.17 Union type handling issues
    18. 22.18 Missing collection type support
    19. 22.19 Missing blueprint syntax validation integration
    20. 22.20 Missing action amount validation
    21. 22.21 Missing token whitelist validation

// Download the full report

Nano Contracts

* Use Google Chrome for best results

** Check "Background Graphics" in the print settings if needed