Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

feat: manual blacklist - IL-264 #147

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

ThomasRalee
Copy link
Collaborator

@ThomasRalee ThomasRalee commented Nov 11, 2024

This PR

Summary by CodeRabbit

  • New Features

    • Introduced a new job step for generating a restriction list in the workflow.
    • Added functionality to generate a list of restricted countries and blacklisted addresses.
    • New script command for generating restriction lists added to the project.
  • Improvements

    • Enhanced readability of the country codes JSON array.
  • Bug Fixes

    • Updated processes to ensure both restricted countries and blacklisted addresses are included in the relevant JSON files.

Copy link

coderabbitai bot commented Nov 11, 2024

Walkthrough

The changes in this pull request introduce a new job step in the GitHub Actions workflow for generating a restriction list, along with the addition of new constants for restricted countries and blacklisted addresses. A new script for generating the restriction list is also created, which updates relevant JSON files. The formatting of the country codes JSON file has been improved for readability. The modifications enhance the functionality related to restrictions and compliance management within the project.

Changes

File Change Summary
.github/workflows/master.yaml Added a new job step "Generate restriction list" using borales/actions-yarn@v4.
json/geo/countries.json Reformatted the JSON array of country codes for improved readability.
ts-scripts/data/geo.ts Introduced a new constant restrictedCountries containing country codes.
ts-scripts/data/ofac.ts Introduced a new constant blacklistedAddresses, initialized as an empty array.
ts-scripts/generateOfacList.ts Modified generateOFACList to include blacklistedAddresses in the JSON output.
ts-scripts/generateRestrictionList.ts Added two functions: generateRestrictedCountries and updateOfacList for JSON updates.
ts-scripts/package.json Added a new script entry "restriction:generate" to execute generateRestrictionList.

Possibly related PRs

  • Autogen OFAC list #59: The changes in ts-scripts/generateOfacList.ts and the introduction of the generateOFACList function are related to the new job step "Generate restriction list" in the main PR, as both involve generating lists that are likely used in similar contexts regarding restrictions and compliance.

Poem

In the land of code where rabbits play,
New lists are born to keep harm at bay.
With countries restricted, and addresses clear,
We hop through the changes, full of cheer!
A script to generate, a workflow anew,
In the garden of code, we flourish and grew! 🐇✨


🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Outside diff range and nitpick comments (4)
ts-scripts/generateRestrictionList.ts (2)

1-3: Consider adding type definitions for imported data.

For better type safety and code maintainability, consider defining and importing types for restrictedCountries and blacklistedAddresses.

+import { RestrictedCountry } from './types/geo'
+import { BlacklistedAddress } from './types/ofac'
 import { readJSONFile, updateJSONFile } from './helper/utils'
-import { restrictedCountries } from './data/geo'
-import { blacklistedAddresses } from './data/ofac'
+import { restrictedCountries } from './data/geo' as RestrictedCountry[]
+import { blacklistedAddresses } from './data/ofac' as BlacklistedAddress[]

1-21: Enhance security and compliance features.

Given that this code handles sensitive compliance data (OFAC lists and geographical restrictions), consider implementing:

  1. Audit logging for all operations
  2. Cryptographic verification of data sources
  3. Backup mechanism before updates
  4. Rate limiting for file operations
  5. Configuration validation

Would you like assistance in implementing these security enhancements?

ts-scripts/generateOfacList.ts (1)

Line range hint 6-8: Enhance error handling and logging for compliance operations.

Since this is compliance-critical code fetching data from an external source, consider these security improvements:

  1. Add explicit error handling for network failures
  2. Log changes for audit purposes
  3. Verify SSL certificate

Consider this enhancement:

+ import { Logger } from '@injectivelabs/utils'
+ 
+ const logger = new Logger('OFAC-List-Generator')

  async function generateOFACList() {
+   try {
      const response = await new HttpClient(
        'https://www.treasury.gov/ofac/downloads/sanctions/1.0/',
+       { 
+         timeout: 10000,
+         rejectUnauthorized: true
+       }
      ).get<{}, { data: string }>('sdn_advanced.xml')
+     
+     logger.info('Successfully fetched OFAC data')
      // ... rest of the function ...
+     
+     const oldList = require('../json/wallets/ofac.json')
+     const newList = [...result, ...blacklistedAddresses]
+     logger.info(`OFAC list updated: ${oldList.length} → ${newList.length} addresses`)
+   } catch (error) {
+     logger.error(`Failed to update OFAC list: ${error.message}`)
+     throw error
+   }
  }
.github/workflows/master.yaml (1)

70-75: Consider additional security measures for compliance data.

Since this step handles sensitive compliance data (blacklists and restrictions):

  1. Consider adding a validation step after generation
  2. Add checksum verification for critical files
  3. Consider implementing approval gates for restriction list changes

Consider adding a validation step after generation:

      - name: Generate restriction list
        uses: borales/actions-yarn@v4
        with:
          cmd: restriction:generate
          dir: "ts-scripts"
+     - name: Validate restriction list
+       uses: borales/actions-yarn@v4
+       with:
+         cmd: restriction:validate
+         dir: "ts-scripts"
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between b08e8c1 and d7fe967.

📒 Files selected for processing (7)
  • .github/workflows/master.yaml (1 hunks)
  • json/geo/countries.json (1 hunks)
  • ts-scripts/data/geo.ts (1 hunks)
  • ts-scripts/data/ofac.ts (1 hunks)
  • ts-scripts/generateOfacList.ts (2 hunks)
  • ts-scripts/generateRestrictionList.ts (1 hunks)
  • ts-scripts/package.json (1 hunks)
✅ Files skipped from review due to trivial changes (3)
  • json/geo/countries.json
  • ts-scripts/data/geo.ts
  • ts-scripts/data/ofac.ts
🔇 Additional comments (4)
ts-scripts/generateOfacList.ts (1)

3-3: Verify the structure and content of blacklistedAddresses.

Since this is compliance-related code dealing with OFAC restrictions, we should ensure the imported data structure is properly typed and validated.

✅ Verification successful

The imported blacklistedAddresses is properly typed and safely used

The implementation shows:

  • blacklistedAddresses is correctly typed as string[] in ofac.ts
  • It's properly used in generateOFACList() to append additional addresses to the OFAC list
  • The addresses are sorted and deduplicated before being written to the JSON file
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the structure and content of blacklistedAddresses

# Check the source file content
echo "Checking source file content:"
cat ts-scripts/data/ofac.ts

# Check if TypeScript types are defined
echo -e "\nChecking for type definitions:"
rg -A 3 "type.*blacklistedAddresses" ts-scripts/data/ofac.ts

Length of output: 287


Script:

#!/bin/bash
# Let's verify how blacklistedAddresses is used in the codebase

# Check the implementation in generateOfacList.ts
echo "Checking generateOfacList.ts implementation:"
cat ts-scripts/generateOfacList.ts

# Find any tests or validation logic
echo -e "\nChecking for related test files:"
fd -e test.ts -e spec.ts generateOfacList

# Look for any TypeScript interfaces or types related to OFAC
echo -e "\nChecking for OFAC-related types:"
rg -i "interface|type.*ofac" --type ts

Length of output: 1769

ts-scripts/package.json (2)

25-25: LGTM! The script follows the established naming convention.

The new restriction:generate script is well-positioned and follows the project's established pattern of category:action naming convention.

Let's verify that the referenced TypeScript file exists:

✅ Verification successful

The generateRestrictionList.ts file exists at the expected location

The script restriction:generate correctly references the TypeScript file located at ts-scripts/generateRestrictionList.ts.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the existence of the generateRestrictionList.ts file
# Expected: File should exist in the ts-scripts directory

fd -t f "generateRestrictionList.ts" ts-scripts/

Length of output: 86


25-25: Consider adding this script to the tokens:generate chain.

Since this is a new restriction list generator, consider whether it should be part of the tokens:generate script chain, especially if the restrictions are token-related.

Let's check if other restriction-related tasks exist in the workflow:

.github/workflows/master.yaml (1)

70-75: Implementation looks good, but needs testing verification.

The new restriction list generation step follows the established pattern and is correctly positioned in the workflow. However, given this handles compliance-related data:

  1. Ensure the restriction:generate script has been thoroughly tested
  2. Verify the generated restriction list format matches expected schema
  3. Confirm the changes are properly validated before being committed

Let's verify the related scripts and configurations:

✅ Verification successful

Implementation verified and properly handles sensitive compliance data

The restriction list generation implementation has been verified and shows:

  1. Proper handling of restricted countries list (CU, IR, KP, SY)
  2. Correct management of OFAC blacklisted addresses
  3. Secure file operations with proper error handling
  4. Consistent data structure in output files (JSON)

The implementation follows security best practices by:

  • Using constant data sources
  • Implementing proper file system checks
  • Maintaining atomic updates
  • Following established JSON schema
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the restriction generation setup

# Check if the script exists and is properly configured
echo "Checking restriction generation script..."
cat ts-scripts/package.json | grep "restriction:generate"

# Verify the JSON schema/structure
echo "Checking JSON files structure..."
find json/ -name "*.json" -type f -exec echo "Found JSON file: {}" \;

Length of output: 2738


Script:

#!/bin/bash
# Let's examine the restriction generation script and related files

# Check the implementation of generateRestrictionList
echo "Checking restriction list generator implementation..."
cat ts-scripts/generateRestrictionList.ts

# Look for any test files related to restrictions
echo -e "\nChecking for test files..."
fd -t f -e test.ts -e spec.ts restriction ts-scripts/

# Check if there's a restriction list output file
echo -e "\nLooking for restriction list output..."
fd -t f restriction -e json json/

Length of output: 976


Script:

#!/bin/bash
# Let's check the data sources and utility functions

# Check the data sources
echo "Checking geo data source..."
cat ts-scripts/data/geo.ts

echo -e "\nChecking OFAC data source..."
cat ts-scripts/data/ofac.ts

# Check utility functions
echo -e "\nChecking utility functions..."
cat ts-scripts/helper/utils.ts

# Check current content of output files
echo -e "\nChecking current countries.json..."
cat json/geo/countries.json

echo -e "\nChecking current ofac.json..."
cat json/wallets/ofac.json

Length of output: 12731

Comment on lines +20 to +21
updateOfacList()
generateRestrictedCountries()
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Implement proper Promise handling for atomic operations.

The current implementation could lead to partial updates if one operation fails. Consider wrapping the executions in a main function with proper error handling.

-updateOfacList()
-generateRestrictedCountries()
+async function main() {
+  try {
+    await Promise.all([
+      updateOfacList(),
+      generateRestrictedCountries()
+    ])
+    console.log('Successfully updated restriction lists')
+  } catch (error) {
+    console.error('Failed to update restriction lists:', error)
+    process.exit(1)
+  }
+}
+
+main()
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
updateOfacList()
generateRestrictedCountries()
async function main() {
try {
await Promise.all([
updateOfacList(),
generateRestrictedCountries()
])
console.log('Successfully updated restriction lists')
} catch (error) {
console.error('Failed to update restriction lists:', error)
process.exit(1)
}
}
main()

Comment on lines +5 to +7
export const generateRestrictedCountries = async () => {
await updateJSONFile('json/geo/countries.json', restrictedCountries)
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add error handling and data validation.

The function should include:

  1. Error handling for file operations
  2. Validation of the restrictedCountries data
  3. Atomic write operation to prevent file corruption
 export const generateRestrictedCountries = async () => {
-  await updateJSONFile('json/geo/countries.json', restrictedCountries)
+  try {
+    if (!Array.isArray(restrictedCountries) || restrictedCountries.length === 0) {
+      throw new Error('Invalid restricted countries data')
+    }
+    
+    await updateJSONFile('json/geo/countries.json', restrictedCountries)
+  } catch (error) {
+    console.error('Failed to generate restricted countries:', error)
+    throw error
+  }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export const generateRestrictedCountries = async () => {
await updateJSONFile('json/geo/countries.json', restrictedCountries)
}
export const generateRestrictedCountries = async () => {
try {
if (!Array.isArray(restrictedCountries) || restrictedCountries.length === 0) {
throw new Error('Invalid restricted countries data')
}
await updateJSONFile('json/geo/countries.json', restrictedCountries)
} catch (error) {
console.error('Failed to generate restricted countries:', error)
throw error
}
}

Comment on lines +9 to +18
export const updateOfacList = async () => {
const wallets = readJSONFile({
path: 'json/wallets/ofac.json'
})

await updateJSONFile('json/wallets/ofac.json', [
...wallets,
...blacklistedAddresses
])
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Enhance OFAC list update logic with validation and deduplication.

Current implementation has several potential issues:

  1. No deduplication of addresses
  2. Missing address format validation
  3. No error handling
  4. Potential memory issues with large lists
 export const updateOfacList = async () => {
+  try {
+    if (!Array.isArray(blacklistedAddresses) || blacklistedAddresses.length === 0) {
+      throw new Error('Invalid blacklisted addresses data')
+    }
+
     const wallets = readJSONFile({
       path: 'json/wallets/ofac.json'
     })
 
+    // Validate wallet addresses format
+    const isValidAddress = (addr: string) => /^0x[a-fA-F0-9]{40}$/.test(addr)
+    if (!blacklistedAddresses.every(isValidAddress)) {
+      throw new Error('Invalid wallet address format detected')
+    }
+
+    // Deduplicate addresses using Set
+    const uniqueAddresses = Array.from(new Set([
+      ...wallets,
+      ...blacklistedAddresses
+    ]))
+
     await updateJSONFile('json/wallets/ofac.json', [
-      ...wallets,
-      ...blacklistedAddresses
+      ...uniqueAddresses
     ])
+  } catch (error) {
+    console.error('Failed to update OFAC list:', error)
+    throw error
+  }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export const updateOfacList = async () => {
const wallets = readJSONFile({
path: 'json/wallets/ofac.json'
})
await updateJSONFile('json/wallets/ofac.json', [
...wallets,
...blacklistedAddresses
])
}
export const updateOfacList = async () => {
try {
if (!Array.isArray(blacklistedAddresses) || blacklistedAddresses.length === 0) {
throw new Error('Invalid blacklisted addresses data')
}
const wallets = readJSONFile({
path: 'json/wallets/ofac.json'
})
// Validate wallet addresses format
const isValidAddress = (addr: string) => /^0x[a-fA-F0-9]{40}$/.test(addr)
if (!blacklistedAddresses.every(isValidAddress)) {
throw new Error('Invalid wallet address format detected')
}
// Deduplicate addresses using Set
const uniqueAddresses = Array.from(new Set([
...wallets,
...blacklistedAddresses
]))
await updateJSONFile('json/wallets/ofac.json', [
...uniqueAddresses
])
} catch (error) {
console.error('Failed to update OFAC list:', error)
throw error
}
}

Comment on lines +22 to +25
await updateJSONFile('json/wallets/ofac.json', [
...result.sort((a, b) => a.localeCompare(b)),
...blacklistedAddresses
])
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Improve data consistency and validation in the combined list.

The current implementation has several potential issues:

  1. No deduplication after combining the arrays
  2. Sorting is only applied to OFAC addresses, not the final list
  3. No validation of blacklisted addresses format

Consider applying this improvement:

  await updateJSONFile('json/wallets/ofac.json', [
-    ...result.sort((a, b) => a.localeCompare(b)),
-    ...blacklistedAddresses
+    ...[...result, ...blacklistedAddresses]
+      .filter((address) => /^0x[a-fA-F0-9]{40}$/i.test(address))
+      .map((address) => address.toLowerCase())
+      .filter((address, index, self) => self.indexOf(address) === index)
+      .sort((a, b) => a.localeCompare(b))
  ])

This change will:

  • Validate all addresses using a regex pattern
  • Convert all addresses to lowercase
  • Remove duplicates from the combined list
  • Sort the final list consistently
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
await updateJSONFile('json/wallets/ofac.json', [
...result.sort((a, b) => a.localeCompare(b)),
...blacklistedAddresses
])
await updateJSONFile('json/wallets/ofac.json', [
...[...result, ...blacklistedAddresses]
.filter((address) => /^0x[a-fA-F0-9]{40}$/i.test(address))
.map((address) => address.toLowerCase())
.filter((address, index, self) => self.indexOf(address) === index)
.sort((a, b) => a.localeCompare(b))
])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant