Skip to content

Commit

Permalink
v3: update all dependencies, clean up code
Browse files Browse the repository at this point in the history
  • Loading branch information
hayzamjs committed Jan 18, 2025
1 parent e424b02 commit 745aa43
Show file tree
Hide file tree
Showing 20 changed files with 1,286 additions and 1,146 deletions.
11 changes: 11 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
Copyright 2025 Haku Labs MTÜ

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
105 changes: 56 additions & 49 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,54 +1,61 @@
.PHONY: default build fmt lint run run_race test clean vet docker_build docker_run docker_clean
.PHONY: default build clean

VERSION := 3.0.0
LIB_NAME := libipfs
SRC := ./${LIB_NAME}.go
BIN_DIR := bin

PLATFORMS := \
linux/amd64 \
freebsd/amd64 \
windows/amd64 \
darwin/amd64 \
darwin/arm64 \
linux/riscv64 \
linux/arm64

# Define cross-compilers for each architecture
CC_COMPILERS := \
freebsd/amd64=clang --target=x86_64-unknown-freebsd \
windows/amd64=x86_64-w64-mingw32-gcc \
linux/amd64=gcc \
linux/arm64=aarch64-linux-gnu-gcc \
linux/riscv64=riscv64-linux-gnu-gcc \
darwin/amd64=o64-clang \
darwin/arm64=o64-clang

# Default target
default: build

# Clean target
clean:
rm -rf bin/ && mkdir bin/

build_linux_x64:
CGO_ENABLED=1 \
GOOS=linux \
GOARCH=amd64 \
go build -buildmode=c-archive -o ./bin/${LIB_NAME}-linux.a ./src/${LIB_NAME}.go

build_linux_arm64:
CGO_ENABLED=1 \
GOOS=linux \
GOARCH=arm64 \
go build -buildmode=c-archive -o ./bin/${LIB_NAME}-linux-arm64.a ./src/${LIB_NAME}.go

build_windows_x64:
CGO_ENABLED=1 \
GOOS=windows \
GOARCH=amd64 \
go build -buildmode=c-archive -o ./bin/${LIB_NAME}-windows.a ./src/${LIB_NAME}.go

build_linux_riscv:
CGO_ENABLED=1 \
GOOS=linux \
GOARCH=riscv64 \
go build -buildmode=c-archive -o ./bin/${LIB_NAME}-linux-riscv64.a ./src/${LIB_NAME}.go

build_darwin_x64:
CGO_ENABLED=1 \
GOOS=darwin \
GOARCH=amd64 \
go build -buildmode=c-archive -o ./bin/${LIB_NAME}-darwin.a ./src/${LIB_NAME}.go

build_darwin_arm64:
CGO_ENABLED=1 \
GOOS=darwin \
GOARCH=arm64 \
go build -buildmode=c-archive -o ./bin/${LIB_NAME}-darwin-arm64.a ./src/${LIB_NAME}.go

build_freebsd_x64:
CGO_ENABLED=1 \
GOOS=freebsd \
GOARCH=amd64 \
go build -buildmode=c-archive -o ./bin/${LIB_NAME}-freebsd.a ./src/${LIB_NAME}.go

build-all: build_linux_x64 build_linux_arm64 build_windows_x64 build_linux_riscv build_darwin_x64 build_darwin_arm64 build_freebsd_x64

build: clean \
build-all
rm -rf $(BIN_DIR)/ && mkdir -p $(BIN_DIR) && cp -rf example.cpp $(BIN_DIR)/

# Function to get the cross-compiler based on GOOS/GOARCH
define GET_CC
$(shell echo $(CC_COMPILERS) | tr ' ' '\n' | grep -E '$(1)/$(2)=' | cut -d= -f2)
endef

# Build rule for each platform
define BUILD_RULE
build_$(1)_$(2):
@echo "Building for $(1)/$(2)..."
$(if $(filter $(1)/$(2),freebsd/amd64), \
env SYSROOT=/usr/local/freebsd-sysroot CGO_CFLAGS="--sysroot=/usr/local/freebsd-sysroot" CGO_LDFLAGS="--sysroot=/usr/local/freebsd-sysroot",) \
CGO_ENABLED=1 \
GOOS=$(1) \
GOARCH=$(2) \
CC=$(call GET_CC,$(1),$(2)) \
go build -buildmode=c-archive -o $(BIN_DIR)/${LIB_NAME}-$(1)-$(2).a $(SRC)
.PHONY: build_$(1)_$(2)
endef

# Generate build rules for all platforms
$(foreach plat, $(PLATFORMS), \
$(eval $(call BUILD_RULE,$(word 1,$(subst /, ,$(plat))),$(word 2,$(subst /, ,$(plat))))))

# Build all platforms
build-all: $(foreach plat, $(PLATFORMS), build_$(subst /,_,$(plat)))

# Main build target
build: clean build-all
80 changes: 29 additions & 51 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,67 +1,45 @@
# libIPFS

A C-style library library that wraps around go-ipfs as a library(not an executable that is embedded) and provides a very simple API.
`libIPFS` is a C-style library that wraps around `go-ipfs` as a library (not an embedded executable) and provides a simple and intuitive API.

## Example

```cpp
#include "libipfs-linux.h"
#include <iostream>

int main() {
std::cout << "Starting IPFS node" << std::endl;
std::cout << IPFSStartNode((char*)"", 0) << std::endl;

std::cout << "Getting peer ID" << std::endl;
std::cout << GetPeerID() << std::endl;

std::cout << "Adding file to IPFS" << std::endl;
std::cout << IpfsAdd((char*)"./test-file.jpg") << std::endl;

std::cout << "Adding directory to IPFS" << std::endl;
std::cout << IpfsAdd((char*)"./test-dir") <<std::endl;

std::cout << "Downloading file from IPFS" << std::endl;
std::cout << IpfsGet((char*)"QmXL7PCYH8VtMxkVTPBXxpnpF893QrLHC5H5AKv2FaAExU", (char*)"./test-download.jpg") << std::endl;

std::cout << "Pinning file to IPFS" << std::endl;
std::cout << IpfsPin((char*)"QmXL7PCYH8VtMxkVTPBXxpnpF893QrLHC5H5AKv2FaAExU") << std::endl;

std::cout << "Locally Pinned Hashes" << std::endl;
std::cout << IpfsGetPinnedHashes() << std::endl;

std::cout << "Resolving /ipns/ipfs.io to IPFS hash" << std::endl;
std::cout << ResolveIPNSName((char*)"/ipns/ipfs.io") << std::endl;
## Building

std::cout << "Publishing to IPNS" << std::endl;
std::cout << PublishIPFSName((char*)"QmXL7PCYH8VtMxkVTPBXxpnpF893QrLHC5H5AKv2FaAExU") << std::endl;
Use the provided `Makefile` to build the library. For example, to build for Linux on `amd64`:

std::cout << "Stopping IPFS node" << std::endl;
std::cout << IPFSStopNode() << std::endl;
}
```bash
make build_linux_amd64
```

## Overview
You can also build for other platforms by specifying the target:

libIPFS is used by the Scala Network Project to retrieve and publish critical information on to IPFS.
```bash
make build_windows_amd64
make build_darwin_amd64
make build_darwin_arm64
make build_linux_riscv64
make build_linux_arm64
make build_freebsd_amd64
```

It runs a *barebones* IPFS instance and provides functions to be called from C/C++.
> **Note:**
> - Cross-compilation has been tested on Debian 12.
> - For FreeBSD builds, you may need a proper sysroot configuration.
> - For macOS builds, `osxcross` is required.
### Why?
## Usage

Currently, no simple implementation or API exists for IPFS in C or C++. Instead of writing, or re-writing, large parts of IPFS in C or C++ we rather use Go and compile it to a C or C++ compatible library. IPFS is implemented in Go already.
An example program, `example.cpp`, is provided in the root of the repository. After building the library, copy the example file to the `bin/` folder and compile it with `g++`:

## Building
```bash
g++ -pthread -o libipfs-example example.cpp libipfs-linux-amd64.a -Wl,--no-as-needed -ldl -lresolv
```

### Requirements
Run the compiled example:

* go >= 1.16
* make >= 4.2.1
* gcc and g++ >= 9.3.0
```bash
./libipfs-example
```

To build the library you can use the following commands, the outputs can be found in bin/
## License

```
go mod download
make build
```
This project is licensed under the terms specified in the [LICENSE](LICENSE) file.
86 changes: 86 additions & 0 deletions example.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
#include "libipfs-linux-amd64.h"
#include <unistd.h>
#include <iostream>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

bool isStatusSuccess(const char* response) {
try {
json parsed = json::parse(response);
return (parsed["Status"] == "success");
} catch (const json::exception& e) {
std::cerr << "JSON Parsing Error: " << e.what() << std::endl;
return false;
}
}

void handleResponse(bool success, const std::string& successMsg, const std::string& errorMsg, const char* response = nullptr) {
if (success) {
std::cout << successMsg << std::endl;
} else {
std::cerr << errorMsg << std::endl;
if (response) {
std::cerr << response << std::endl;
}
}
}

void performAction(char* (*actionFunc)(char*), const std::string& arg, const std::string& actionName) {
const char* response = actionFunc((char*)arg.c_str());
handleResponse(isStatusSuccess(response), actionName + " succeeded", actionName + " failed", response);
}

void performAction(char* (*actionFunc)(), const std::string& actionName) {
const char* response = actionFunc();
handleResponse(isStatusSuccess(response), actionName + " succeeded", actionName + " failed", response);
}

int main() {
std::cout << "Starting IPFS from C++ Land ..." << std::endl;
const char* startResponse = Start((char*)"./ipfs", 16969);

std::cout << "Add Peer" << std::endl;
performAction(AddPeer, "/ip4/104.131.131.82/udp/4001/quic-v1/p2p/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ", "Add Peer");

sleep(5);

std::cout << "Remove Peer" << std::endl;
performAction(RemovePeer, "/ip4/104.131.131.82/udp/4001/quic-v1/p2p/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ", "Remove Peer");

try {
json parsedStart = json::parse(startResponse);
std::string peerId = parsedStart["Data"]["peerId"];
std::cout << "Started with Peer ID: " << peerId << std::endl;

const char* addResponse = Add((char*)"/home/hayzam/Projects/libipfs-new/bin/example.cpp");
json parsedAdd = json::parse(addResponse);
std::string cid = parsedAdd["Data"]["cid"];
std::cout << "Added example.cpp file -> CID: " << cid << std::endl;

performAction(Pin, cid, "Pin CID");

std::cout << "Sleeping for a bit after pinning..." << std::endl;
sleep(5);

performAction(Unpin, cid, "Unpin CID");
performAction(GarbageCollect, "Garbage Collect");

const std::string targetPath = "./downloaded.txt";
const std::string getCid = "/ipfs/bafybeifx7yeb55armcsxwwitkymga5xf53dxiarykms3ygqic223w5sk3m";
if (!isStatusSuccess(Get((char*)getCid.c_str(), (char*)targetPath.c_str(), true))) {
std::cerr << "Failed to get CID: " << getCid << std::endl;
} else {
std::cout << "Got CID: " << getCid << " and saved to " << targetPath << std::endl;
}

sleep(60);

std::cout << Stop() << std::endl;
} catch (const json::exception& e) {
std::cerr << "JSON Parsing Error: " << e.what() << std::endl;
return 1;
}

return 0;
}
20 changes: 0 additions & 20 deletions example/Makefile

This file was deleted.

34 changes: 0 additions & 34 deletions example/example.cpp

This file was deleted.

Binary file removed example/test-file.jpg
Binary file not shown.
Loading

0 comments on commit 745aa43

Please sign in to comment.