Blockchain Project Report
Blockchain Project Report
Blockchain Technology
A Report Submitted
in Partial Fulfilment of the Requirements
for the Seminar
by
List of Figures 5
List of Tables 6
1 Introduction 1
1.1 Motivation and Background . . . . . . . . . . . . . . . . . . . 1
1.2 System Overview . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.2.1 Blockchain Layer . . . . . . . . . . . . . . . . . . . . . 2
1.2.2 Cryptographic Service . . . . . . . . . . . . . . . . . . 3
1.2.3 API Gateway . . . . . . . . . . . . . . . . . . . . . . . 4
1.2.4 Web Interface . . . . . . . . . . . . . . . . . . . . . . . 4
1.3 Key Contributions . . . . . . . . . . . . . . . . . . . . . . . . 4
1
2.3 Security Properties . . . . . . . . . . . . . . . . . . . . . . . . 10
2.3.1 Confidentiality . . . . . . . . . . . . . . . . . . . . . . 10
2.3.2 Unidirectionality . . . . . . . . . . . . . . . . . . . . . 11
2.3.3 Collusion Resistance . . . . . . . . . . . . . . . . . . . 12
2.3.4 Verifiability . . . . . . . . . . . . . . . . . . . . . . . . 13
3 Implementation Details 14
3.1 Smart Contract Design . . . . . . . . . . . . . . . . . . . . . . 14
3.1.1 CabShareCore Contract . . . . . . . . . . . . . . . . . 14
3.1.2 Reputation System . . . . . . . . . . . . . . . . . . . . 17
3.1.3 DPoS Delegate Hub . . . . . . . . . . . . . . . . . . . . 18
3.2 Cryptographic Service Implementation . . . . . . . . . . . . . 20
3.2.1 Windows-Compatible CP-ABE . . . . . . . . . . . . . 20
3.2.2 Encryption with Policy . . . . . . . . . . . . . . . . . . 21
3.2.3 Policy Matching . . . . . . . . . . . . . . . . . . . . . . 23
3.2.4 Proxy Re-encryption . . . . . . . . . . . . . . . . . . . 23
3.3 Web Application . . . . . . . . . . . . . . . . . . . . . . . . . 25
3.3.1 MetaMask Integration . . . . . . . . . . . . . . . . . . 25
3.3.2 Direct Smart Contract Interaction . . . . . . . . . . . . 26
2
4.3 Performance Benchmarks . . . . . . . . . . . . . . . . . . . . . 34
4.3.1 Encryption Performance . . . . . . . . . . . . . . . . . 34
4.3.2 Smart Contract Gas Costs . . . . . . . . . . . . . . . . 35
7 Conclusion 46
3
8 Code Repository Structure 48
9 API Reference 50
9.1 Crypto Service API . . . . . . . . . . . . . . . . . . . . . . . . 50
9.1.1 POST /api/crypto/setup . . . . . . . . . . . . . . . . . 50
9.1.2 POST /api/crypto/encrypt . . . . . . . . . . . . . . . 51
9.2 Ride API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
9.2.1 POST /api/rides . . . . . . . . . . . . . . . . . . . . . 51
9.2.2 POST /api/rides/:id/proposals . . . . . . . . . . . . . 52
9.2.3 POST /api/rides/:id/match . . . . . . . . . . . . . . . 52
9.2.4 GET /api/rides/pool . . . . . . . . . . . . . . . . . . . 52
Bibliography 53
4
List of Figures
5
List of Tables
6
Chapter 1
Introduction
1
• Trust Requirements: Users must trust the central authority to han-
dle their data responsibly and fairly.
2
• Reputation: Tracks and updates reputation scores for riders, drivers,
and administrators using the formula Scorei+1 = Scorei + F where
F ∈ {−1, 1, 2}.
3
1.2.3 API Gateway
• Rider Interface: Create ride requests with encrypted details and re-
quired driver attributes
4
1. Complete Cryptographic Implementation: All eight CP-ABE
algorithms fully implemented with Windows compatibility using Py-
Cryptodome
5
Chapter 2
6
2.2 Data Flow and Interaction Patterns
When a rider creates a new ride request, the following sequence occurs:
7
2.2.2 Driver Proposal Submission
The matching process involves both off-chain policy verification and on-chain
state updates:
8
2. Frontend sends match request to API Gateway with:
• Ride ID
• Driver’s attributes
• Load original CT
7. Re-encrypt ciphertext:
• Store CT ′ off-chain
• Compute CT ′ hash
9
• Verifies driver has active proposal
2.3.1 Confidentiality
10
The actual ciphertext CT is stored off-chain in the API Gateway’s file
system. The createRide() function only accepts and stores hashes, making
it impossible to reconstruct plaintext from on-chain data.
2.3.2 Unidirectionality
11
2.3.3 Collusion Resistance
12
2.3.4 Verifiability
Proof. The verification algorithm computes the expected value of R′′ inde-
pendently:
1 def verify ( self , ct_prime ) :
2 ct_prime_data = json . loads ( ct_prime . ct_prime )
3
4 # Recompute F from CT ’ and verify R ’’
5 f_hash = hashlib . sha256 (
6 ct_prime_data [ ’ reenc_key ’ ]. encode ()
7 ) . hexdigest ()
8 expected_r = hashlib . sha256 (
9 f_hash . encode ()
10 ) . hexdigest ()
11
12 return expected_r == ct_prime . r_double_prime
If R′′ does not match the expected value, either the ciphertext was tam-
pered with or generated incorrectly. The driver can reject the decryption,
preventing potential attacks.
13
Chapter 3
Implementation Details
14
Ride Creation
1 function createRide (
2 bytes32 rideId ,
3 bytes32 ctHash ,
4 Types . AccessPolicy calldata policy
5 ) external payable override nonReentrant {
6 require (! rideExists [ rideId ] , " Ride already exists " ) ;
7 require ( ctHash != bytes32 (0) , " Invalid CT hash " ) ;
8
9 // Lock rider deposit
10 depositsContract . lockRiderDeposit { value : msg . value }(
11 rideId ,
12 msg . sender
13 );
14
15 rides [ rideId ] = Types . Ride ({
16 rideId : rideId ,
17 rider : msg . sender ,
18 ctHash : ctHash ,
19 policy : policy ,
20 status : Types . RideStatus . Requested ,
21 createdAt : block . timestamp
22 // ... other fields
23 }) ;
24
25 emit RideRequested ( rideId , msg . sender , ctHash , policy .
policyRef ) ;
26 }
15
• nonReentrant modifier prevents reentrancy attacks
Driver Matching
1 function matchDriver (
2 bytes32 rideId ,
3 address driver
4 ) external override o n lyA d mi n O rD e le g at e
5 rideInStatus ( rideId , Types . RideStatus . Proposed ) {
6
7 // Verify driver has active proposal
8 bool hasProposal = false ;
9 Types . Proposal [] storage proposals = rideProposals [ rideId
];
10
11 for ( uint256 i = 0; i < proposals . length ; i ++) {
12 if ( proposals [ i ]. driver == driver && proposals [ i ].
active ) {
13 hasProposal = true ;
14 break ;
15 }
16 }
17 require ( hasProposal , " Driver has no active proposal " ) ;
18
19 // Update state
20 rides [ rideId ]. driver = driver ;
21 rides [ rideId ]. status = Types . RideStatus . Matched ;
16
22
23 // Refund non - selected drivers
24 for ( uint256 i = 0; i < proposals . length ; i ++) {
25 if ( proposals [ i ]. driver != driver ) {
26 depositsContract . r e fu n dD r i ve r De p os i t (
27 rideId ,
28 proposals [ i ]. driver
29 );
30 }
31 }
32
33 emit DriverMatched ( rideId , driver , msg . sender ) ;
34 }
where F ∈ {−1, 1, 2} and clamp function ensures scores remain in [0, 1000].
For administrators:
Scorei + 1 if validation succeeds
admin
Scorei+1
admin = (3.2)
Scorei − 1 if validation fails
admin
1 function rateDriver (
17
2 bytes32 rideId ,
3 address driver ,
4 int8 F
5 ) external override onlyAuthorized {
6 require ( F == -1 || F == 1 || F == 2 , " Invalid F value " ) ;
7
8 _initializeUser ( driver ) ;
9 uint256 currentScore = driverScores [ driver ];
10 uint256 newScore ;
11
12 if ( F < 0) {
13 uint256 decrease = uint256 ( - int256 ( F ) ) ;
14 newScore = currentScore > decrease
15 ? currentScore - decrease
16 : MIN_SCORE ;
17 } else {
18 uint256 increase = uint256 ( int256 ( F ) ) ;
19 newScore = currentScore + increase ;
20 if ( newScore > MAX_SCORE ) newScore = MAX_SCORE ;
21 }
22
23 driverScores [ driver ] = newScore ;
24 emit DriverRated ( driver , rideId , F , newScore ) ;
25 }
18
2 require ( i s D e l e g a t e R eg i s t e r e d [ delegate ] , " Not registered " )
;
3
4 // Remove previous vote
5 address previousDelegate = voterToDelegate [ msg . sender ];
6 if ( previousDelegate != address (0) ) {
7 uint256 prevWeight = re pu ta tio nC on tra ct
8 . get Se le cti on We igh t ( msg . sender ) ;
9 deleg ateVoteC ount [ previousDelegate ] -= prevWeight ;
10 }
11
12 // Add new vote with reputation weight
13 uint256 weight = re put at io nCo nt ra ct
14 . g etS el ec tio nW ei ght ( msg . sender ) ;
15 voterToDelegate [ msg . sender ] = delegate ;
16 d elegateV oteCount [ delegate ] += weight ;
17
18 emit DelegateVoted ( msg . sender , delegate , weight ) ;
19 _ up d a te T op D e le g at e s () ;
20 }
19
9 batch . negativeVotes ++;
10 }
11
12 address [] memory topDelegates = getTopDelegates () ;
13 uint256 totalDelegates = topDelegates . length ;
14 uint256 requ iredAppr ovals =
15 ( totalDelegates * 2) / 3 + 1; // > 2/3 threshold
16
17 if ( batch . positiveVotes >= requi redAppro vals ) {
18 batch . validated = true ;
19 emit BatchValidated ( batchId , true , ...) ;
20 r ep uta ti on Con tr ac t . bumpAdminScore ( batch . proposer ,
true ) ;
21 }
22 }
20
8 public_key = master_key . public_key ()
9
10 params = {
11 ’ curve ’: ’P -256 ’ ,
12 ’ master_secret ’: master_key . export_key (
13 format = ’ DER ’
14 ) . hex () ,
15 ’ public_key ’: public_key . export_key (
16 format = ’ DER ’
17 ) . hex () ,
18 ’g ’: public_key . pointQ . x
19 }
20
21 self . params = SystemParams (
22 pk = json . dumps ({
23 ’ public_key ’: params [ ’ public_key ’] ,
24 ’g ’: str ( params [ ’g ’ ])
25 }) ,
26 mk = params [ ’ master_secret ’]
27 )
28 return self . params
The encryption algorithm uses AES-GCM for message encryption with attribute-
based key derivation:
1 def encrypt ( self , plaintext : str , policy : AccessPolicy ) :
2 # Generate symmetric key
3 aes_key = get_random_bytes (32)
21
4
5 # Encrypt with AES - GCM
6 cipher = AES . new ( aes_key , AES . MODE_GCM )
7 ciphertext , tag = cipher . e nc ry pt_ an d_ dig es t (
8 plaintext . encode ( ’utf -8 ’)
9 )
10
11 # Create key shares for each policy row
12 key_shares = {}
13 for i , row in enumerate ( policy . matrix ) :
14 attr = policy . rho [ i ]
15
16 # Derive attribute - specific key share
17 h = HMAC . new ( aes_key , digestmod = SHA256 )
18 h . update ( attr . encode ( ’utf -8 ’) )
19 h . update ( str ( row ) . encode ( ’utf -8 ’) )
20
21 key_shares [ attr ] = {
22 ’ share ’: h . hexdigest () ,
23 ’ row ’: row
24 }
25
26 ct_data = {
27 ’ ciphertext ’: ciphertext . hex () ,
28 ’ tag ’: tag . hex () ,
29 ’ nonce ’: cipher . nonce . hex () ,
30 ’ key_shares ’: key_shares
31 }
32
33 return Ciphertext (
22
34 ct = json . dumps ( ct_data ) ,
35 policy = policy ,
36 ct_hash = compute_hash ( ct_data )
37 )
For more complex policies with matrix structure, the algorithm would
solve a linear system to verify satisfiability.
23
9 )
10 h . update ( ct_data [ ’ aes_key _encrypt ed ’ ]. encode () )
11 reenc_key = h . hexdigest ()
12
13 # Create transformed ciphertext
14 ct_prime_data = {
15 ’ ciphertext ’: ct_data [ ’ ciphertext ’] ,
16 ’ tag ’: ct_data [ ’ tag ’] ,
17 ’ nonce ’: ct_data [ ’ nonce ’] ,
18 ’ reenc_key ’: reenc_key ,
19 ’ ptid_to ’: rk_data [ ’ ptid_driver ’]
20 }
21
22 # Generate verification component
23 f_hash = hashlib . sha256 (
24 rk_data [ ’ reenc_key ’ ]. encode ()
25 ) . hexdigest ()
26 r_double_prime = hashlib . sha256 (
27 f_hash . encode ()
28 ) . hexdigest ()
29
30 return R e e n c r y p t e d C i p h e r t e x t (
31 ct_prime = json . dumps ( ct_prime_data ) ,
32 ct_prime_hash = compute_hash ( ct_prime_data ) ,
33 r_double_prime = r_double_prime
34 )
24
3.3 Web Application
25
26 { children }
27 </ WalletContext . Provider >
28 );
29 };
26
23 arrivalTime : Math . floor ( Date . now () / 1000) + 3600 ,
24 route : ’ Optimal route ’ ,
25 availableSeats : tripData . availableSeats ,
26 pricePerSeat : ethers . parseEther ( tripData . pricePerSeat ) ,
27 attributes : hashedAttributes
28 };
29
30 const minDeposit = ethers . parseEther ( ’ 0.02 ’) ;
31
32 // MetaMask prompts user to sign
33 const tx = await contract . proposeRide (
34 rideId ,
35 trip ,
36 { value : minDeposit }
37 );
38
39 // Wait for confirmation
40 const receipt = await tx . wait () ;
41
42 setResult ({
43 success : true ,
44 txHash : receipt . hash ,
45 blockNumber : receipt . blockNumber
46 }) ;
47 };
27
Chapter 4
28
12
13 const policy = {
14 policyHash : ethers . keccak256 (
15 ethers . toUtf8Bytes ( " policy " )
16 ),
17 policyRef : " ipfs :// test " ,
18 earliestArrival : 0 ,
19 latestArrival : Math . floor ( Date . now () / 1000) + 86400 ,
20 minAttributes : 2
21 };
22
23 await expect (
24 cabShareCore . createRide ( rideId , ctHash , policy , {
25 value : minDeposit
26 })
27 ) . to . emit ( cabShareCore , " RideRequested " )
28 . withArgs ( rideId , rider . address , ctHash , policy .
policyRef ) ;
29
30 const ride = await cabShareCore . getRide ( rideId ) ;
31 expect ( ride . status ) . to . equal (0) ; // Requested
32 }) ;
33
34 it ( " Should accept driver proposal with deposit " , async ()
=> {
35 const [ , driver ] = await ethers . getSigners () ;
36 const driverDeposit = ethers . parseEther ( " 0.02 " ) ;
37
38 const trip = {
39 departureTime : Math . floor ( Date . now () / 1000) ,
29
40 destination : " Airport " ,
41 arrivalTime : Math . floor ( Date . now () / 1000) + 3600 ,
42 route : " Highway " ,
43 availableSeats : 3 ,
44 pricePerSeat : ethers . parseEther ( " 0.01 " ) ,
45 attributes : [
46 ethers . keccak256 ( ethers . toUtf8Bytes ( " verified_driver "
)),
47 ethers . keccak256 ( ethers . toUtf8Bytes ( " 5 star_rating " ) )
48 ]
49 };
50
51 await expect (
52 cabShareCore . connect ( driver ) . proposeRide ( rideId , trip ,
{
53 value : driverDeposit
54 })
55 ) . to . emit ( cabShareCore , " DriverProposed " ) ;
56 }) ;
57 }) ;
30
8 expect ( ride . ctHash . length ) . to . equal (66) ; // 0 x + 64 hex
chars
9
10 // Plaintext should not be recoverable from on - chain data
11 const blockchainState = await ethers . provider . getStorage (
12 await cabShareCore . getAddress () ,
13 ethers . keccak256 ( ethers . toUtf8Bytes ( " rides " ) )
14 );
15
16 // State should not contain readable plaintext
17 expect ( blockchainState ) . to . not . include ( " Pickup " ) ;
18 expect ( blockchainState ) . to . not . include ( " Destination " ) ;
19 }) ;
20
21 it ( " Should enforce access control on matching " , async () = >
{
22 const [ , , unauthorized ] = await ethers . getSigners () ;
23
24 await expect (
25 cabShareCore . connect ( unauthorized ) . matchDriver (
26 rideId ,
27 driverAddress
28 )
29 ) . to . be . revertedWith ( " Not authorized " ) ;
30 }) ;
31
32 it ( " Should prevent double rating " , async () = > {
33 await cabShareCore . rateDriver ( rideId , 1) ; // F = 1
34
35 await expect (
31
36 cabShareCore . rateDriver ( rideId , 2)
37 ) . to . be . revertedWith ( " Already rated " ) ;
38 }) ;
39 }) ;
1 def t e s t _ e n c r y p t _ d e c r y p t _ c y c l e () :
2 engine = CPABEProxyReenc ()
3 params = engine . setup ()
4
5 # Generate user keys
6 attributes = [ ’ verified_driver ’ , ’5 star_rating ’]
7 user_keys = engine . keygen ( attributes , ’ driver -123 ’)
8
9 # Create policy
10 policy = AccessPolicy (
11 matrix =[[1] , [1]] ,
12 rho ={0: ’ verified_driver ’ , 1: ’5 star_rating ’}
13 )
14
15 # Encrypt
16 plaintext = " Pickup : Downtown , Destination : Airport "
17 ct = engine . encrypt ( plaintext , policy )
18
19 assert ct . ct_hash is not None
20 assert len ( ct . ct_hash ) == 64 # SHA -256 hex
32
21
22 # Generate re - encryption key
23 rk = engine . generate_rekey (
24 user_keys ,
25 user_keys . sk ,
26 user_keys . ptid
27 )
28
29 # Re - encrypt
30 ct_prime = engine . reencrypt ( ct , rk )
31
32 # Verify
33 assert engine . verify ( ct_prime )
34
35 # Decrypt
36 decrypted = engine . decrypt ( ct_prime , user_keys )
37 assert decrypted == plaintext
38
39 def t e s t _ u n i d i r e c t i o n a l i t y () :
40 " " " Verify CT ’ cannot be reversed to CT " " "
41 ct = engine . encrypt ( plaintext , policy )
42 ct_prime = engine . reencrypt ( ct , rk )
43
44 # Attempt to reverse ( should fail )
45 with pytest . raises ( ValueError ) :
46 rever se_trans form ( ct_prime , rk )
47
48 def t e s t _ c o l l u s i o n _ r e s i s t a n c e () :
49 " " " Admin + unmatched driver cannot decrypt " " "
33
50 matched_keys = engine . keygen ( attributes , ’ matched - driver ’
)
51 unmatched_keys = engine . keygen ( attributes , ’ unmatched -
driver ’)
52
53 ct = engine . encrypt ( plaintext , policy )
54 rk = engine . generate_rekey (
55 rider_keys ,
56 matched_keys . sk ,
57 matched_keys . ptid
58 )
59 ct_prime = engine . reencrypt ( ct , rk )
60
61 # Matched driver can decrypt
62 assert engine . decrypt ( ct_prime , matched_keys ) ==
plaintext
63
64 # Unmatched driver cannot decrypt ( verification fails )
65 with pytest . raises ( ValueError , match = " Verification failed
"):
66 engine . decrypt ( ct_prime , unmatched_keys )
34
Attributes Encrypt (ms) ReEncrypt (ms) Decrypt (ms)
2 12.3 8.7 15.1
5 18.9 14.2 22.4
10 31.5 23.8 38.7
20 58.3 42.1 71.2
50 132.7 98.3 165.4
The gas costs are reasonable for a production system. The most expensive
operation is ride creation due to storage initialization.
35
Chapter 5
5.1.1 Prerequisites
36
2. Install [Link] dependencies:
1 npm install
2 cd contracts && npm install && cd ..
3 cd api && npm install && cd ..
4 cd web && npm install && cd ..
4. Configure environment:
1 cp . env . example . env
2 # Edit . env with deployment addresses
37
Expected output:
7. Configure MetaMask:
38
• Add Hardhat network: RPC URL [Link] Chain
ID 31337
• Pickup location
• Destination
• Departure date/time
39
5.3.2 Driver Workflow
5. Specify:
• Own attributes
• Destination compatibility
• Available seats
40
4. For each proposal:
6. System automatically:
• Transforms CT to CT’
41
Chapter 6
42
5. DPoS Consensus: Top delegates validated by community through
reputation-weighted voting provide application-level governance.
43
4. Gas Costs: While reasonable, gas costs may be prohibitive during
network congestion.
44
6.4 Lessons Learned
45
Chapter 7
Conclusion
46
theoretically sound but also practically achievable with current technology.
While challenges remain in scalability and cryptographic strength, the foun-
dation established here provides a solid basis for future development.
As blockchain technology matures and Layer 2 solutions improve, de-
centralized applications like this cab-sharing system have the potential to
disrupt traditional centralized platforms, returning control and privacy to
users while maintaining security and efficiency.
47
Chapter 8
cab-share/
contracts/ # Solidity smart contracts
contracts/
[Link]
[Link]
[Link]
[Link]
libraries/[Link]
test/ # Contract tests
scripts/[Link] # Deployment script
48
[Link] # API endpoints
[Link] # Documentation
49
Chapter 9
API Reference
1 {
2 " success " : true ,
3 " params " : {
4 " pk " : "..." ,
5 " initialized " : true
6 }
7 }
50
9.1.2 POST /api/crypto/encrypt
1 {
2 " plaintext " : " Pickup : Downtown , Destination :
Airport " ,
3 " policy " : {
4 " matrix " : [ [ 1 ] , [ 1 ] ] ,
5 " rho " : { " 0 " : " verified_driver " , " 1 " : " 5
star_rating " }
6 }
7 }
Response:
1 {
2 " success " : true ,
3 " ciphertext " : { ... } ,
4 " ct_hash " : " 0 x ..."
5 }
51
9.2.2 POST /api/rides/:id/proposals
52
Bibliography
53
Full Paper.
54
[14] V. Goyal, O. Pandey, A. Sahai, and B. Waters. Attribute-based encryp-
tion for fine-grained access control of encrypted data. In ACM Confer-
ence on Computer and Communications Security, pages 89–98. ACM,
2006.
[15] Feon Jaison and Suhas R. Chandra. Peer to peer carpooling using
blockchain. International Journal of Advanced Research in Computer
and Communication Engineering, 12(3):42–47, March 2023. Impact Fac-
tor 7.918, ISO 3297:2007 Certified.
[18] Meta Platforms. React: A JavaScript Library for Building User Inter-
faces, 2023. Version 18.2.0.
[22] Pallets Projects. Flask: The Python Micro Framework for Building Web
Applications, 2023. Version 2.3.0.
55
[23] Ricmoo. [Link]: Complete Ethereum Library and Wallet Implemen-
tation, 2024. Version 6.10.0.
[27] VoidZero Inc. Vite: Next Generation Frontend Tooling, 2024. Version
5.0.0.
56