iExec RLC 백서

iExec RLC

원문

bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 12쪽 중 6쪽

ect download links (not web pages) Security : Files are public - don't use for sensitive data 4. Requester Secrets ​ What they are: Confidential data provided by the user running your iApp. When to use: API keys, database credentials, authentication tokens that the user needs to provide. How to Access Requester Secrets ​ Secrets are available as environment variables with the pattern IEXEC_REQUESTER_SECRET_<INDEX> : Python JavaScript python import os # Access requester secrets by index api_key = os.environ.get( 'IEXEC_REQUESTER_SECRET_1' ) db_password = os.environ.get( 'IEXEC_REQUESTER_SECRET_2' ) if api_key: # Use the API key for external service calls headers = { 'Authorization' : f 'Bearer { api_key } ' } # Make API calls... else : print ( "No API key provided" ) javascript // Access requester secrets by index const apiKey = process.env. IEXEC_REQUESTER_SECRET_1 ; const dbPassword = process.env. IEXEC_REQUESTER_SECRET_2 ; if (apiKey) { // Use the API key for external service calls const headers = { Authorization: `Bearer ${ apiKey }` }; // Make API calls... } else { console. log ( 'No API key provided' ); } How Users Provide Requester Secrets ​ Users provide all Requester Secrets when executing your iApp via DataProtector: ts // Example: User executes your iApp with all input types const processProtectedDataResponse = await dataProtectorCore . processProtectedData ({ protectedData : '0x123abc...' , // Protected data address app : '0x456def...' , // Your iApp address args : 'model=bert threshold=0.8' , // Public arguments secrets : { // Requester secrets 1 : 'sk-1234567890abcdef' , // API key 2 : 'mydbpassword123' , // DB password }, }); 5. App Secrets ​ What they are: App Secrets are confidential data owned by the iApp developer that are provisioned during app deployment and made available to your iApp during execution. They are stored securely in the Secret Management Service (SMS) and only accessible within the Trusted Execution Environment (TEE). When to use: Use App Secrets for API keys, private keys, tokens, database credentials, or any sensitive data that belongs to the app developer and needs to be available to the iApp during execution. Unlike Requester Secrets (which are provided by users), App Secrets are configured once by the developer and remain constant across all executions. INFO App Secrets are different from Requester Secrets: App Secrets : Owned by the app developer, configured once during deployment Requester Secrets : Owned by the user executing the iApp, provided per execution How to Use App Secrets in Your iApp ​ App Secrets are configured in your iapp.config.json during development and automatically deployed with your iApp. For deployment details, see the Build Your iApp guide . Configuration in iapp.config.json ​ Add your App Secret to the project configuration: json { "defaultChain" : "arbitrum" , "projectName" : "my-iapp" , "template" : "JavaScript" , "appSecret" : "{ \" API_KEY \" : \" sk-1234567890abcdef \" , \" DATABASE_URL \" : \" postgresql://user:pass@host:5432/db \" }" } WARNING Size limit : App secrets are limited to 4096 kB maximum Immutable : Once set, app secrets cannot be changed without redeploying the iApp Security : App secrets are encrypted and only accessible within the TEE environment Ownership : App secrets belong to the iApp developer, not the user executing the iApp How to Access App Secrets ​ App secrets are exposed as environment variables following the IEXEC_APP_DEVELOPER_SECRET naming pattern. Python JavaScript python import os import json # Get your app secret app_secret = os.environ.get( 'IEXEC_APP_DEVELOPER_SECRET' ) if app_secret: # Parse JSON (multiple secrets) secrets = json.loads(app_secret) api_key = secrets.get( 'API_KEY' ) database_url = secrets.get( 'DATABASE_URL' ) javascript // Get your app secret const appSecret = process.env. IEXEC_APP_DEVELOPER_SECRET ; if (appSecret) { // Parse JSON (multiple secrets) const secrets = JSON . parse (appSecret); const apiKey = secrets. API_KEY ; const databaseUrl = secrets. DATABASE_URL ; } Testing Inputs Locally ​ Use iApp Generator to test different input types: bash # Test with different input types iapp test --args "model=bert threshold=0.8" # Test with arguments iapp test --inputFiles "https://example.com/data.json" # Test with input files iapp test --secrets "key1=value1,key2=value2" # Test with secrets # Mock protected data for testing iapp mock protectedData # Generate sample protected data # Test your iApp locally with mocked protected data iapp test --protectedData "mock_name" Common Patterns ​ Data Analysis iApp ​ User execution (DataProtector): ts // User runs your data analysis iApp const response = await dataProtectorCore . processProtectedData ({ protectedData : '0x123abc...' , // Their business data app : '0x456def...' , // Your analysis iApp args : 'analysis_type=sentiment period=monthly' , secrets : { 1 : 'api-key-for-external-service' }, }); Your iApp code (Python): python # Access inputs in your iApp args = sys.argv[ 1 :] # Processing parameters api_key = os.environ.get( 'IEXEC_REQUESTER_SECRET_1' ) # User's API access protected_data = load_protected_data() # The sensitive data to process # Process and output results results = analyze_data(protected_data, args, api_key) save_results(results) AI Model iApp ​ User execution (DataProtector): ts // User runs your AI model with their data const response = await dataProtectorCore . processProtectedData ({ protectedData : '0x123abc...' , // Their personal data app : '0x456def...' , // Your AI model iApp inputFiles : [ 'https://example.com/model-weights.pkl' ], args : 'model_type=classification confidence_threshold=0.8' , }); Your iApp code (Python): python # Load model from input files model = load_model_from_inputs() # Get user data to process user_data = load_protected_data() # Run inference predictions = model.predict(user_data) # Return encrypted results save_encrypted_results(predictions) Report Generator iApp ​ User execution (DataProtector): ts // User generates a report from their business data const response = await dataProtectorCore . processProtectedData ({ protectedData : '0x123abc...' , // Their business data app : '0x456def...' , // Your report generator iApp args : 'report_type=quarterly format=pdf include_charts=true' , inputFiles : [ 'https://example.com/company-template.xlsx' ], }); Your iApp code (Python): python # Get configuration from args report_type = get_arg( 'type' , default = 'summary' ) # Access the business data business_data = load_protected_data() # Generate report report = generate_report(business_data, report_type) save_report(report) What's Next? ​ You now understand all input types available to your iApp! Continue building with these guides: Outputs - Learn how to generate and structure your iApp outputs App Access Control and Pricing - Control who can use your iApp Debugging Your iApp - Troubleshoot execution issues ## /guides/build-iapp/outputs Outputs ​ Your iApp must generate outputs that users can retrieve and decrypt. Understanding how to structure your outputs, create the required metadata, and follow best practices is essential for building effective privacy-preserving applications. This guide covers how to generate outputs from your iApp and ensure they can be properly retrieved by users. Creating Outputs ​ Your iApp must generate outputs in the IEXEC_OUT directory. Every iApp must create a computed.json file with metadata about the computation. Basic Output Structure ​ Python JavaScript python import os import json # Get output directory iexec_out = os.environ[ 'IEXEC_OUT' ] # Create your result file result_data = { "analysis" : "positive sentiment" , "confidence" : 0.92 , "processed_at" : "2024-01-15T10:30:00Z" } # Save main result with open ( f " { iexec_out } /result.json" , 'w' ) as f: json.dump(result_data, f) # REQUIRED: Create `computed.json` metadata computed_metadata = { "deterministic-output-path" : f " { iexec_out } /result.json" , "execution-timestamp" : "2024-01-15T10:30:00Z" , "app-version" : "1.0.0" } with open ( f " { iexec_out } /computed.json" , 'w' ) as f: json.dump(computed_metadata, f) javascript const fs = require ( 'fs' ); const path = require ( 'path' ); // Get output directory const iexecOut = process.env. IEXEC_OUT ; // Create your result file const resultData = { analysis: 'positive sentiment' , confidence: 0.92 , processed_at: '2024-01-15T10:30:00Z' , }; // Save main result fs. writeFileSync ( path. join (iexecOut, 'result.json' ), JSON . stringify (resultData, null , 2 ) ); // REQUIRED: Create computed.json metadata const computedMetadata = { 'deterministic-output-path' : path. join (iexecOut, 'result.json' ), 'execution-timestamp' : '2024-01-15T10:30:00Z' , 'app-version' : '1.0.0' , }; fs. writeFileSync ( path. join (iexecOut, 'computed.json' ), JSON . stringify (computedMetadata, null , 2 ) ); Output Best Practices ​ Always create computed.json - This is mandatory Use descriptive filenames - analysis_result.json , not output.txt Include metadata - Timestamps, versions, parameters used Structure your data - Use JSON for structured results Keep files reasonable - Large outputs increase retrieval time and may hit memory limits Memory awareness - TEE enclave memory is limited, avoid generating multi-GB outputs Example: Multi-file Output ​ python import os import json iexec_out = os.environ[ 'IEXEC_OUT' ] # Create multiple output files summary = { "total_processed" : 1000 , "success_rate" : 0.95 } with open ( f " { iexec_out } /summary.json" , 'w' ) as f: json.dump(summary, f) # Create a detailed report with open ( f " { iexec_out } /detailed_report.txt" , 'w' ) as f: f.write( "Detailed analysis results... \n " ) # Create visualization data chart_data = { "labels" : [ "A" , "B" , "C" ], "values" : [ 10 , 20 , 30 ]} with open ( f " { iexec_out } /chart_data.json" , 'w' ) as f: json.dump(chart_data, f) # Required metadata file computed = { "deterministic-output-path" : f " { iexec_out } /summary.json" , "additional-files" : [ f " { iexec_out } /detailed_report.txt" , f " { iexec_out } /chart_data.json" ] } with open ( f " { iexec_out } /computed.json" , 'w' ) as f: json.dump(computed, f) What's Next? ​ You now understand how to generate proper outputs from your iApp! Continue building with these guides: Inputs - Learn about the different input types available to your iApp App Access Control and Pricing - Control who can use your iApp Debugging Your iApp - Troubleshoot execution issues ## /guides/build-iapp/debugging Debugging ​ When your iApp doesn't work as expected, debugging in the TEE environment requires specific techniques. This guide helps you identify issues and optimize your iApp's performance. Task Execution Lifecycle ​ Understanding how your task progresses through the iExec network: Key Stages ​ Deal Creation - Orders matched, funds locked Task Initialization - Workers selected for execution iApp Execution - Your code runs inside TEE Result Processing - Results encrypted and uploaded Task Completion - Results available for download Most failures happen during stages 2-4 Monitoring your Tasks ​ iExec Explorer ​ Track your tasks at iExec Explorer : Search by taskId or deal ID Check status: PENDING → ACTIVE → COMPLETED/FAILED View error messages if execution fails Status in Code ​ ts const response = await dataProtectorCore . processProtectedData ({ protectedData : '0x123abc...' , app : '0x456def...' , onStatusUpdate : ({ title , isDone }) => { console . log ( `Status: ${ title } - Done: ${ isDone }` ); }, }); Debug Commands ​ Local Testing ​ bash # Test your iApp locally iapp test --args "model=bert threshold=0.8" iapp test --secrets "key1=value1,key2=value2" # Mock protected data for testing iapp mock protectedData iapp test --protectedData "mock_name" Remote Debugging ​ bash # Deploy and run iapp deploy iapp run < iapp-addres s > # Debug failed executions iapp debug < taskI d > Task Information ​ bash # View task details iexec task show < taskI d > # Download results (if completed) iexec task show < taskI d > --download Common Issues ​ Task Timeout ​ Cause : Code takes too long to execute Solution : Optimize algorithms, reduce input sizes, use appropriate task category Memory Issues ​ Cause : Loading large files, memory leaks, TEE constraints Solution : Process data in chunks, use streaming, optimize memory usage Input/Output Problems ​ Cause : Wrong file paths, missing computed.json Solution : Always create computed.json , verify environment variables python # Always create computed.json import json, os computed = { "deterministic-output-path" : f " { os.environ[ 'IEXEC_OUT' ] } /result.json" } with open ( f " { os.environ[ 'IEXEC_OUT' ] } /computed.json" , 'w' ) as f: json.dump(computed, f) Dataset Type Unmatching ​ Cause : The dataset type specified in the frontend (protectData) does not match with the dataset type specified in the iApp Solution : Check both dataset types Best Practices ​ Input Validation ​ python import os, sys # Check required environment variables if not os.environ.get( 'IEXEC_IN' ) or not os.environ.get( 'IEXEC_OUT' ): print ( "ERROR: Missing IEXEC_IN or IEXEC_OUT" ) sys.exit( 1 ) # Validate arguments if len (sys.argv) < 2 : print ( "ERROR: Missing required arguments" ) sys.exit( 1 ) Clear Error Messages ​ python try : # Your processing logic result = process_data(data) except Exception as e: print ( f "ERROR: Processing failed: {str (e) } " ) sys.exit( 1 ) Safe File Operations ​ python import os, json # Always ensure output directory exists iexec_out = os.environ[ 'IEXEC_OUT' ] os.makedirs(iexec_out, exist_ok = True ) # Write results safely try : with open ( f " { iexec_out } /result.json" , 'w' ) as f: json.dump(result_data, f) except Exception as e: print ( f "ERROR: Failed to write results: { e } " ) sys.exit( 1 ) What's Next? ​ Continue improving your iApp: Inputs - Handle data inputs Outputs - Handle data outputs in TEE ## /guides/build-iapp/advanced/quick-start Quick Start ​ This tutorial shows how to create decentralized app over the iExec infrastructure. iExec enables decentralized docker app deployment and monetization on the blockchain. This guide uses the iExec SDK command-line interface to deploy an iExec app on a test blockchain. Install the iExec SDK ​ For complete installation instructions and requirements, see the iExec SDK documentation . Requirements: bash npm -g install iexec # install the CLI iexec --version iexec --help Create your identity on the blockchain ​ On the blockchain, your identity is defined by your wallet, consisting of cryptographically encrypted private key and public address. What you own on the blockchain is associated with your address. The applications you deploy on iExec are associated with your wallet. Let's set up your wallet. Create a new Wallet file text iexec wallet create You will be asked to choose a password to protect your wallet, don't forget it since there is no way to recover it. The SDK creates a wallet file that contains a randomly generated private key encrypted by the chosen password and the derived public address. Make sure to back up the wallet file in a safe place and write down your address. Your wallet is stored in the ethereum keystore, the location depends on your OS: On Linux: ~/.ethereum/keystore On Mac : ~/Library/Ethereum/keystore On Windows: ~/AppData/Roaming/Ethereum/keystore Wallet file name follow the pattern UTC--<CREATION_DATE>--<ADDRESS> INFO iExec SDK uses standard Ethereum wallet, you can reuse or import existing Ethereum wallet. See iExec SDK documentation wallet command . What's next? ​ You are now familiar with the following key iExec concepts for developers: Your wallet is your on-chain ID and blockchain account You can deploy decentralized applications on iExec Anyone can run tasks against payment in RLC on iExec Payments are processed by the decentralized platform between users' iExec Accounts Resource governance is managed by orders Continue with these guides: Learn how to build your first confidential application running on iExec ## /guides/build-iapp/advanced/build-your-first-tdx-iapp Build your first TDX iApp ​ In this tutorial, you will learn how to build and run a Confidential Computing app with Intel TDX (Trust Domain Extensions) on the iExec protocol. Prerequisites Docker 17.05 or higher on the daemon and client. iExec SDK 8.24.0 or higher. Familiarity with the basics of Intel TDX and the iExec workflow described in Deploy and run an iApp . Unlike the legacy SGX/SCONE flow, TDX does not require a separate sconification step: you build a standard linux/amd64 OCI image, push it to a registry, and configure the iExec app for the TDX framework (see Intel TDX Technology for what TDX provides). Prepare your app ​ For this tutorial, create a new directory tree. Execute the following commands in ~/iexec-projects/ : bash cd ~/iexec-projects mkdir tee-hello-world-tdx && cd tee-hello-world-tdx iexec init --skip-wallet mkdir src touch Dockerfile Write the iApp logic ​ Develop your code logic as below. The following examples use JavaScript and Python for brevity; any workload that fits in a Docker image can be used on iExec. Copy the following content in src/ . src/app.js src/app.py javascript const fsPromises = require ( 'fs' ).promises; ( async () => { try { const iexecOut = process.env. IEXEC_OUT ; // Do whatever you want (let's write hello world here) const message = process.argv. length > 2 ? process.argv[ 2 ] : 'World' ; const text = `Hello, ${ message }!` ; console. log (text); // Append some results in /iexec_out/ await fsPromises. writeFile ( `${ iexecOut }/result.txt` , text); // Declare everything is computed const computedJsonObj = { 'deterministic-output-path' : `${ iexecOut }/result.txt` , }; await fsPromises. writeFile ( `${ iexecOut }/computed.json` , JSON . stringify (computedJsonObj) ); } catch (e) { console. log (e); process. exit ( 1 ); } })(); python import os import sys import json iexec_out = os.environ[ 'IEXEC_OUT' ] # Do whatever you want (let's write hello world here) text = 'Hello, {} !' .format(sys.argv[ 1 ] if len (sys.argv) > 1 else "World" ) print (text) # Append some results in /iexec_out/ with open (iexec_out + '/result.txt' , 'w+' ) as fout: fout.write(text) # Declare everything is computed with open (iexec_out + '/computed.json' , 'w+' ) as f: json.dump({ "deterministic-output-path" : iexec_out + '/result.txt' }, f) WARNING As a developer, make it a rule to never log sensitive information in your application. Execution logs are accessible by: worker(s) involved in the task the workerpool manager the requester of the task Dockerize your iApp ​ Copy the following content in Dockerfile . Dockerfile for JavaScript Dockerfile for Python bash FROM node:22-alpine3.21 ### install your dependencies if you have some RUN mkdir /app && cd /app COPY ./src /app ENTRYPOINT [ "node", "/app/app.js"] bash FROM python:3.13.3-alpine3.21 ### install python dependencies if you have some COPY ./src /app ENTRYPOINT [ "python3" , "/app/app.py"] Build the docker image. WARNING iExec expects your Docker container to be built
프로젝트로 돌아가기